âŽī¸ LAG() is a SQL window function that returns the value from a previous row within the same result set. It allows you to compare the current row with one or more preceding rows without using self-joins or complex subqueries.
đ What is LAG()?
LAG() accesses data from a row that comes before the current row, based on the ordering defined in the OVER() clause. This makes it ideal for identifying changes, calculating differences, and performing time-series analysis.
Information
đ¯ Why Use LAG()?
LAG() makes it easy to compare current values with previous values without writing complex SQL.
- đ Compare current and previous rows.
- đ Calculate growth or decline.
- đ Detect changes over time.
- đ Analyze trends and historical data.
- đ Eliminate the need for self-joins.
đ Sample Table
| Month | Sales |
|---|---|
| January | 10000 |
| February | 12000 |
| March | 11000 |
| April | 15000 |
đ Basic Syntax
LAG() Syntax
LAG(expression [, offset [, default_value]])
OVER (
[PARTITION BY column_name]
ORDER BY column_name
)| Argument | Description |
|---|---|
| expression | The value to retrieve from a previous row. |
| offset | Number of rows to look back. Default is 1. |
| default_value | Returned when no previous row exists. |
đĄ Example: Previous Month's Sales
Basic LAG() Example
SELECT
Month,
Sales,
LAG(Sales) OVER (
ORDER BY Month
) AS PreviousSales
FROM MonthlySales;đ Example Output
| Month | Sales | PreviousSales |
|---|---|---|
| January | 10000 | NULL |
| February | 12000 | 10000 |
| March | 11000 | 12000 |
| April | 15000 | 11000 |
Remember
đĄ Example: Calculate Monthly Sales Difference
Compare Current and Previous Sales
SELECT
Month,
Sales,
Sales - LAG(Sales) OVER (
ORDER BY Month
) AS SalesDifference
FROM MonthlySales;đ Example Output
| Month | Sales | SalesDifference |
|---|---|---|
| January | 10000 | NULL |
| February | 12000 | 2000 |
| March | 11000 | -1000 |
| April | 15000 | 4000 |
đĄ Example: Use a Custom Offset
Retrieve the value from two rows earlier.
LAG() with Offset
SELECT
Month,
Sales,
LAG(Sales, 2) OVER (
ORDER BY Month
) AS SalesTwoMonthsAgo
FROM MonthlySales;đĄ Example: Use a Default Value
Instead of returning NULL, return 0 when no previous row exists.
LAG() with Default Value
SELECT
Month,
Sales,
LAG(Sales, 1, 0) OVER (
ORDER BY Month
) AS PreviousSales
FROM MonthlySales;đĄ Example: Partition Data
Restart previous-row calculations for each department.
LAG() with PARTITION BY
SELECT
Department,
EmployeeName,
Salary,
LAG(Salary) OVER (
PARTITION BY Department
ORDER BY Salary
) AS PreviousSalary
FROM Employees;âī¸ LAG() vs LEAD()
| Function | Accesses |
|---|---|
| LAG() | Previous row(s). |
| LEAD() | Next row(s). |
đŧ Real-World Applications
- đ Compare monthly or yearly sales.
- đš Analyze stock price movements.
- đĻ Compare account balances over time.
- đĄī¸ Measure changes in weather data.
- đ Build trend and growth reports.
- đĻ Compare inventory levels between reporting periods.
đī¸ Database Compatibility
| Database System | LAG() Support |
|---|---|
| MySQL | â Supported in MySQL 8.0 and later. |
| PostgreSQL | â Fully supported. |
| SQL Server | â Supported (SQL Server 2012 and later). |
| Oracle | â Fully supported. |
| SQLite | â Supported in SQLite 3.25.0 and later. |
â ī¸ Common Mistakes
- â Omitting the ORDER BY clause inside OVER().
- â Assuming the first row always has a previous value.
- â Using the wrong offset.
- â Forgetting PARTITION BY when calculations should restart for each group.
Warning
â ī¸ Best Practices
Best Practice
đ Key Points to Remember
- đ LAG() retrieves values from previous rows.
- đ It is a SQL window function.
- đ The default offset is 1.
- đ You can specify a custom offset and default value.
- đ PARTITION BY restarts calculations within groups.
- đ It is ideal for trend analysis, comparisons, and time-series reporting.