Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 07 / Topic 3 of 8

LAG and LEAD

LAG(col) reads the previous row's value (by the window's order); LEAD(col) the next. The classic: days between a customer's consecutive orders —

SELECT customer_id, order_date,
       order_date - LAG(order_date) OVER (PARTITION BY customer_id
                                          ORDER BY order_date) AS days_since_prev
FROM orders
WHERE customer_id IN (1, 2)
ORDER BY customer_id, order_date;
 customer_id | order_date | days_since_prev 
-------------+------------+-----------------
           1 | 2025-01-10 |                
           1 | 2025-02-14 |              35
           1 | 2025-03-30 |              44
           2 | 2025-01-25 |                
           2 | 2025-03-18 |              52
(5 rows)

Each first order has no previous row, so its LAG is NULL — honest, and exactly what COALESCE or an optional third argument (LAG(order_date, 1, NULL) takes offset and default) is for. Month-over-month growth, "did the price change since last revision?", session gaps — every compare this row with its neighbour question is a LAG/LEAD question, and Part 8 builds the growth report on it.

🧪 Quick quiz — answer from memory, then check.

  1. What does LAG return for the first row of a partition?
  2. Which function reads the next row?
Show the answers
  1. NULL (or the default you pass as its third argument).
  2. LEAD.

Exercise 3: Asha's rhythm

What to do: For customer 1 only, each order with the days since her previous one.

Sample output:

 order_id | order_date | days_since_prev 
----------+------------+-----------------
        1 | 2025-01-10 |                
        3 | 2025-02-14 |              35
        7 | 2025-03-30 |              44
(3 rows)

💡 Hint: order_date - LAG(order_date) OVER (ORDER BY order_date) — the first row's blank is LAG's honest NULL.


Show the solution to Exercise 3
-- Exercise 3: Asha's rhythm
SELECT order_id, order_date,
       order_date - LAG(order_date) OVER (ORDER BY order_date) AS days_since_prev
FROM orders
WHERE customer_id = 1
ORDER BY order_date;

Search the guide