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

OrderIDOrderDateAmountPrevAmountNextAmount
1012024-01-05245.5NULL89.9
1022024-01-1289.9245.5412
1032024-02-0341289.956.25
1042024-02-1856.25412150
1052024-03-0115056.25320.75
1062024-03-09320.7515027
1072024-03-2227320.75198.4
1082024-04-02198.427NULL

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

MonthRevenueChangePctChange
2024-01335.4NULLNULL
2024-02468.25132.8539.6
2024-03497.7529.56.3
2024-04198.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

CustomerIDOrderDateDaysSincePrev
12024-01-05NULL
12024-02-1844
22024-02-03NULL
32024-03-09NULL
42024-01-12NULL
42024-03-2270
52024-03-01NULL
72024-04-02NULL