Careeroza
LAG & LEAD
Looking at Neighbouring Rows
LAG(col, n, default) returns the value from n rows before the current row; LEAD looks ahead. The default n is 1.
Example
Each order with the previous and next order amount:
SELECT OrderID, OrderDate, Amount,
LAG(Amount) OVER (ORDER BY OrderDate) AS PrevAmount,
LEAD(Amount) OVER (ORDER BY OrderDate) AS NextAmount
FROM Orders;Result: 8 rows
| OrderID | OrderDate | Amount | PrevAmount | NextAmount |
|---|---|---|---|---|
| 101 | 2024-01-05 | 245.5 | NULL | 89.9 |
| 102 | 2024-01-12 | 89.9 | 245.5 | 412 |
| 103 | 2024-02-03 | 412 | 89.9 | 56.25 |
| 104 | 2024-02-18 | 56.25 | 412 | 150 |
| 105 | 2024-03-01 | 150 | 56.25 | 320.75 |
| 106 | 2024-03-09 | 320.75 | 150 | 27 |
| 107 | 2024-03-22 | 27 | 320.75 | 198.4 |
| 108 | 2024-04-02 | 198.4 | 27 | NULL |
Change Over Time
Example
Month-over-month revenue change:
WITH Monthly AS (
SELECT strftime('%Y-%m', OrderDate) AS Month, SUM(Amount) AS Revenue
FROM Orders GROUP BY Month
)
SELECT Month, Revenue,
Revenue - LAG(Revenue) OVER (ORDER BY Month) AS Change,
ROUND(100.0 * (Revenue - LAG(Revenue) OVER (ORDER BY Month)) / LAG(Revenue) OVER (ORDER BY Month), 1) AS PctChange
FROM Monthly;Result: 4 rows
| Month | Revenue | Change | PctChange |
|---|---|---|---|
| 2024-01 | 335.4 | NULL | NULL |
| 2024-02 | 468.25 | 132.85 | 39.6 |
| 2024-03 | 497.75 | 29.5 | 6.3 |
| 2024-04 | 198.4 | -299.35 | -60.1 |
Per Group
Example
Days since the same customer's previous order (compare with the self-join version in Medium → SELF JOIN):
SELECT CustomerID, OrderDate,
julianday(OrderDate) - julianday(LAG(OrderDate) OVER (PARTITION BY CustomerID ORDER BY OrderDate)) AS DaysSincePrev
FROM Orders
ORDER BY CustomerID, OrderDate;Result: 8 rows
| CustomerID | OrderDate | DaysSincePrev |
|---|---|---|
| 1 | 2024-01-05 | NULL |
| 1 | 2024-02-18 | 44 |
| 2 | 2024-02-03 | NULL |
| 3 | 2024-03-09 | NULL |
| 4 | 2024-01-12 | NULL |
| 4 | 2024-03-22 | 70 |
| 5 | 2024-03-01 | NULL |
| 7 | 2024-04-02 | NULL |