skip to today's puzzle

LAG brings the previous row alongside

Starting table: cafe_sales

Starting cafe_sales data before the example query
monthsales
2026-01120
2026-02150
2026-03140

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

monthsalesprevious
2026-01120NULL
2026-02150120
2026-03140150

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