LAG brings the previous row alongside
Starting table: cafe_sales
| month | sales |
|---|---|
| 2026-01 | 120 |
| 2026-02 | 150 |
| 2026-03 | 140 |
LAG reads a value from the previous row in the order you put inside OVER. At Rowan's café, monthly sales can sit beside the previous month's sales without joining another table. The first row has no previous row, so its previous value is NULL. LAG means the previous recorded row, not necessarily the previous calendar month — gaps in the data still matter.
A tiny example
In plain English: Show me each month’s sales next to the sales from the month before it.
SELECT month, sales, LAG(sales) OVER (ORDER BY month) AS previous
FROM cafe_sales
ORDER BY month;Query result
| month | sales | previous |
|---|---|---|
| 2026-01 | 120 | NULL |
| 2026-02 | 150 | 120 |
| 2026-03 | 140 | 150 |
January has no previous row. February sees January's 120; March sees February's 150.
Related SQL lessons
Ready for a break?
A fresh, bite-sized SQL puzzle waits every morning. Tap tiles, see real results. No terminal, no setup, no timers.
Try today's free SQL puzzle