skipnothing/SQL

LAG, LEAD & Frames

Five orders from one customer sit in orders, sorted by date. Each row knows its own amount but not what came just before it, so the answer to 'bigger or smaller than last time' is sitting one row up.

  • ▸Comparing each order to the one before it needs no self-join, and the very first row comes back empty.
  • ▸Like last topic's month ordering, a tie stalls a running total: two same-day orders share one sum instead of climbing.
  • ▸Two ways to measure where the sum stops match exactly until two orders tie on the sort column.
BUILDS ON
01

The Row Before and After

Five orders from one customer, sorted oldest first. To ask whether an order beat the one before it, you need the previous row's amount sitting on the current row. A window function fetches exactly that, no self-join:

SELECT created_at, amount,
       LAG(amount)  OVER (ORDER BY created_at, id) AS prev_amount,
       LEAD(amount) OVER (ORDER BY created_at, id) AS next_amount
FROM orders WHERE user_id = 1;
-- created_at   amount   prev_amount   next_amount
-- 2026-01-05   40.00    NULL          25.00
-- 2026-01-12   25.00    40.00         55.00
-- 2026-01-12   55.00    25.00         60.00
-- 2026-02-02   60.00    55.00         30.00
-- 2026-02-15   30.00    60.00         NULL

LAG(amount) reads the amount one row back in the sorted order; LEAD(amount) reads one row forward. The very first row has nothing behind it, so its prev_amount is NULL; the last row has nothing ahead, so its next_amount is NULL. Pass a second number, LAG(amount, 2), to step two rows back instead of one, and a third, LAG(amount, 1, 0), to fill that edge with 0 rather than NULL. The order inside OVER is what defines "before" and "after", drop it and neither word means anything.

BUILD THE CHANGE COLUMN FROM TILES

Keep going, sign up to unlock the rest

3 more parts in this topic, plus 30+ more topics in SQL.

Sign up, it's freeSee the full SQL