LAG, LEAD, FIRST_VALUE & LAST_VALUE
LAG – the previous row's value
lag(column, offset, default) OVER (PARTITION BY … ORDER BY …)
lag(amount)→ the amount from the previous rowlag(amount, 2)→ two rows backlag(amount, 1, 0)→ use 0 instead of NULL for the first row
LEAD – the next row's value
lead(amount) → the amount from the following row. Same arguments as lag.
Typical calculations
- Change:
amount - lag(amount) - Growth %:
round(100.0 * (total - lag(total)) / lag(total), 1) - Gap between events:
spent_on - lag(spent_on)→ days since the previous expense - Next due date, previous login, session detection
FIRST_VALUE, LAST_VALUE, NTH_VALUE
first_value(title) OVER (PARTITION BY user_id ORDER BY spent_on)→ the user's first ever expense, on every rowlast_value(…)⚠️ by default the window frame ends at the current row, so last_value returns the current row! Add a frame:ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING(or usefirst_valuewith the order reversed)nth_value(title, 2)→ the 2nd value
Partition carefully
Without PARTITION BY user_id, lag would compare Asha's first expense with Ravi's last one. Always partition by the entity you're tracking.
Month-over-month pattern ⭐
- Aggregate per month (GROUP BY or CTE)
- Apply
lag(total) OVER (ORDER BY month) - Calculate the change
Example
-- Days since each user's previous expense
SELECT user_id, title, spent_on,
lag(spent_on) OVER (PARTITION BY user_id ORDER BY spent_on) AS previous,
spent_on - lag(spent_on) OVER (PARTITION BY user_id ORDER BY spent_on) AS days_gap
FROM expenses
WHERE user_id = 4
ORDER BY spent_on;
-- Bike service | 2026-09-08 | NULL | NULL
-- Groceries | 2026-09-25 | 2026-09-08 | 17 ...
-- Month-over-month change ⭐
WITH monthly AS (
SELECT date_trunc('month', spent_on)::date AS month, sum(amount) AS total
FROM expenses
GROUP BY 1
)
SELECT to_char(month, 'Mon YYYY') AS month_label,
total,
lag(total) OVER (ORDER BY month) AS prev_month,
total - lag(total) OVER (ORDER BY month) AS change,
round(100.0 * (total - lag(total) OVER (ORDER BY month))
/ lag(total) OVER (ORDER BY month), 1) AS growth_pct
FROM monthly
ORDER BY month;
-- Sep 2026 | 18230.00 | NULL | NULL | NULL
-- Oct 2026 | 26090.00 | 18230.00 | 7860.00 | 43.1
-- Nov 2026 | 32290.00 | 26090.00 | 6200.00 | 23.8
-- LEAD: what did the user buy next?
SELECT title, spent_on, lead(title) OVER (ORDER BY spent_on) AS next_purchase
FROM expenses WHERE user_id = 2;
-- FIRST_VALUE and LAST_VALUE (with the full frame!)
SELECT user_id, title, spent_on,
first_value(title) OVER w AS first_expense,
last_value(title) OVER (w ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS latest_expense
FROM expenses
WHERE user_id = 2
WINDOW w AS (PARTITION BY user_id ORDER BY spent_on)
ORDER BY spent_on;