0PricingLogin
SQL Academy · Lesson

LAG, LEAD and Time-Series Patterns

Compare each row to its previous or next sibling with LAG and LEAD, and build period-over-period deltas.

LAG and LEAD: Look Backwards / Forwards

These access neighbouring rows in the window:

  • LAG(col, n, default) — value n rows before the current row
  • LEAD(col, n, default) — value n rows after

Previous Row

Compare each order to the previous one for the same user:

SELECT id, user_id, created_at, total,
       LAG(total) OVER (
         PARTITION BY user_id ORDER BY created_at
       ) AS prev_total
FROM orders;

All lessons in this course

  1. OVER, PARTITION BY, ORDER BY
  2. ROW_NUMBER, RANK, DENSE_RANK
  3. LAG, LEAD and Time-Series Patterns
  4. Running Totals and Moving Averages
← Back to SQL Academy