SQL LAG and LEAD

LAG returns a value from a previous row, LEAD from a following row, according to the window's ORDER BY. They are the standard tools for month-over-month or day-over-day comparisons.

Syntax

LAG(col) OVER (ORDER BY date_col)
LEAD(col, 1, 0) OVER (ORDER BY date_col)

Try it yourself

Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.

lag-lead.sql · PostgreSQL
Loading editor…

Examples

1. Month over month

WITH m AS (SELECT DATE_TRUNC('month', order_date)::date AS month, COUNT(*) AS n FROM orders GROUP BY 1) SELECT month, n, LAG(n) OVER (ORDER BY month) AS prev, n - LAG(n) OVER (ORDER BY month) AS change FROM m ORDER BY month;

Monthly orders and the change from the previous month.

Common mistakes

  • Forgetting ORDER BY inside OVER, so "previous" has no meaning.

Practice: test yourself

This challenge is from our interactive course. Write the query and press Check answer.

Challenge · 30 pts

For 2025, return each month (first day, as a date), its order count, and the previous month's order count, in month order.

challenge.sql · PostgreSQL
Loading editor…

FAQ

What does LAG return for the first row?

NULL, unless you pass a default as the third argument.

Learn SQL step by step

65 hands-on exercises, streaks, a leaderboard and a certificate.

Start free →