LAG() and LEAD() let a row look at the row before or after it, which is how SQL calculates month-over-month changes and the time between orders. Together with FIRST_VALUE(), LAST_VALUE(), NTILE(), PERCENT_RANK(), and aggregates used as window functions, they cover almost every “compare this row with others” question without a self join.

Part 1 on window functions introduced OVER(), PARTITION BY, running totals, rankings, and moving averages. This lesson adds the functions you’ll reach for next, the ones that compare a row with its neighbors or place it within a group.

The examples use the Learn SQL series’ sample database: download shop.sql and load it as shown in Part 1 of the series. Everything was tested on PostgreSQL, MySQL 8, SQL Server, and SQLite.

LAG: Look at the Previous Row

LAG(column) returns the value of column from the previous row in the window. What was each customer’s previous order date?

SELECT customer_id,
       order_id,
       order_date,
       LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) AS previous_order
FROM orders
WHERE customer_id IN (1, 2, 3)
ORDER BY customer_id, order_date;
 customer_id | order_id | order_date | previous_order
-------------+----------+------------+----------------
           1 |      101 | 2025-08-02 |
           1 |      103 | 2025-08-11 | 2025-08-02
           1 |      112 | 2025-11-02 | 2025-08-11
           2 |      102 | 2025-08-05 |
           2 |      106 | 2025-09-07 | 2025-08-05
           3 |      104 | 2025-08-19 |
           3 |      110 | 2025-10-10 | 2025-08-19
  • ORDER BY order_date inside OVER() defines what “previous” means. Without it, SQL Server rejects the query, and the other databases pick an unpredictable order.
  • PARTITION BY customer_id restarts the window for each customer, so Maria’s first order doesn’t look back at someone else’s.
  • Each customer’s first order has no previous row, so LAG returns NULL.

To get the number of days between orders, subtract the two dates with your database’s date function from the date and time functions lesson, for example order_date - LAG(order_date) OVER (...) in PostgreSQL or DATEDIFF(day, LAG(order_date) OVER (...), order_date) in SQL Server.

LEAD: Look at the Next Row

LEAD() is the mirror image: it looks ahead.

SELECT customer_id,
       order_id,
       order_date,
       LEAD(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) AS next_order
FROM orders
WHERE customer_id IN (1, 2, 3)
ORDER BY customer_id, order_date;
 customer_id | order_id | order_date | next_order
-------------+----------+------------+------------
           1 |      101 | 2025-08-02 | 2025-08-11
           1 |      103 | 2025-08-11 | 2025-11-02
           1 |      112 | 2025-11-02 |
           2 |      102 | 2025-08-05 | 2025-09-07
           2 |      106 | 2025-09-07 |
           3 |      104 | 2025-08-19 | 2025-10-10
           3 |      110 | 2025-10-10 |

A NULL in next_order marks each customer’s latest order. Rows where LEAD is NULL are a quick way to find “the last thing that happened” for each customer, product, or account.

Offsets and Defaults

Both functions take two optional arguments: how many rows to move (default 1) and what to return when there’s no such row (default NULL):

SELECT order_id,
       order_date,
       quantity,
       LAG(quantity, 1, 0) OVER (ORDER BY order_date) AS previous_quantity,
       LAG(quantity, 2)    OVER (ORDER BY order_date) AS two_orders_ago
FROM orders
WHERE order_id <= 104
ORDER BY order_date;
 order_id | order_date | quantity | previous_quantity | two_orders_ago
----------+------------+----------+-------------------+----------------
      101 | 2025-08-02 |        1 |                 0 |
      102 | 2025-08-05 |        3 |                 1 |
      103 | 2025-08-11 |        2 |                 3 |              1
      104 | 2025-08-19 |        1 |                 2 |              3

LAG(quantity, 1, 0) returns 0 instead of NULL for the first row. LAG(quantity, 2) looks two rows back. Notice that the WHERE filter runs before the window function, so the window only sees orders 101 to 104.

Month-over-Month Change

The most common use of LAG is comparing each period with the one before. First total shipped revenue by month in a CTE, then compare:

WITH monthly AS (
    SELECT SUBSTRING(CAST(o.order_date AS CHAR(10)), 1, 7) AS month,
           SUM(o.quantity * p.price) AS revenue
    FROM orders o
    JOIN products p ON p.product_id = o.product_id
    WHERE o.status = 'shipped'
    GROUP BY SUBSTRING(CAST(o.order_date AS CHAR(10)), 1, 7)
)
SELECT month,
       revenue,
       LAG(revenue) OVER (ORDER BY month) AS previous_month,
       revenue - LAG(revenue) OVER (ORDER BY month) AS difference,
       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
             / LAG(revenue) OVER (ORDER BY month), 1) AS pct_change
FROM monthly
ORDER BY month;
  month  | revenue | previous_month | difference | pct_change
---------+---------+----------------+------------+------------
 2025-08 | 1384.00 |                |            |
 2025-09 | 1218.00 |        1384.00 |    -166.00 |      -12.0
 2025-10 | 2047.00 |        1218.00 |     829.00 |       68.1

Revenue fell 12% in September and rose 68.1% in October. A few notes:

  • SUBSTRING(CAST(order_date AS CHAR(10)), 1, 7) turns a date like 2025-08-02 into 2025-08. It’s a portable trick that works in all four databases; in your own database you might prefer DATE_TRUNC('month', ...) (PostgreSQL), DATE_FORMAT(..., '%Y-%m') (MySQL), strftime('%Y-%m', ...) (SQLite), or FORMAT(..., 'yyyy-MM') (SQL Server).
  • 100.0 (not 100) avoids integer division, as explained in the aggregate functions lesson.
  • If the previous month’s revenue could be 0, wrap the divisor in NULLIF(..., 0) to avoid a division-by-zero error.
  • A month with no sales is missing entirely, so LAG would compare October with August. Fill the gaps first with a calendar, as shown in the self joins and cross joins lesson.

Filtering on a Window Function

Window functions run after WHERE, so you can’t filter on them directly. Calculate them in a CTE, then filter. Which orders were repeat purchases?

WITH ordered AS (
    SELECT customer_id,
           order_id,
           order_date,
           LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) AS previous_order
    FROM orders
)
SELECT customer_id, order_id, order_date
FROM ordered
WHERE previous_order IS NOT NULL
ORDER BY customer_id, order_date;
 customer_id | order_id | order_date
-------------+----------+------------
           1 |      103 | 2025-08-11
           1 |      112 | 2025-11-02
           2 |      106 | 2025-09-07
           3 |      110 | 2025-10-10
           5 |      111 | 2025-10-21

The same CTE pattern works for “the latest order per customer” (LEAD(...) IS NULL) or “the first order per customer” (ROW_NUMBER() = 1, from Part 1).

FIRST_VALUE and LAST_VALUE

FIRST_VALUE() returns the first value in the window. What was each customer’s first purchase?

SELECT c.first_name,
       o.order_date,
       p.name AS product,
       FIRST_VALUE(p.name) OVER (PARTITION BY o.customer_id ORDER BY o.order_date) AS first_product
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
JOIN products p  ON p.product_id = o.product_id
WHERE o.customer_id IN (1, 3)
ORDER BY c.first_name, o.order_date;
 first_name | order_date | product  | first_product
------------+------------+----------+---------------
 Maria      | 2025-08-02 | Laptop   | Laptop
 Maria      | 2025-08-11 | Keyboard | Laptop
 Maria      | 2025-11-02 | Desk     | Laptop
 Sofia      | 2025-08-19 | Desk     | Desk
 Sofia      | 2025-10-10 | Monitor  | Desk

Now try LAST_VALUE() the same way, to get each customer’s latest purchase:

SELECT c.first_name,
       o.order_date,
       p.name AS product,
       LAST_VALUE(p.name) OVER (PARTITION BY o.customer_id ORDER BY o.order_date) AS last_product
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
JOIN products p  ON p.product_id = o.product_id
WHERE o.customer_id IN (1, 3)
ORDER BY c.first_name, o.order_date;
 first_name | order_date | product  | last_product
------------+------------+----------+--------------
 Maria      | 2025-08-02 | Laptop   | Laptop
 Maria      | 2025-08-11 | Keyboard | Keyboard
 Maria      | 2025-11-02 | Desk     | Desk
 Sofia      | 2025-08-19 | Desk     | Desk
 Sofia      | 2025-10-10 | Monitor  | Monitor

That’s wrong: last_product just repeats each row’s own product. The reason is the default frame. When a window has an ORDER BY, it only reaches from the first row up to the current row, so the “last” row in the window is always the current one. Extend the frame to the end of the partition:

SELECT c.first_name,
       o.order_date,
       p.name AS product,
       LAST_VALUE(p.name) OVER (
           PARTITION BY o.customer_id
           ORDER BY o.order_date
           ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
       ) AS last_product
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
JOIN products p  ON p.product_id = o.product_id
WHERE o.customer_id IN (1, 3)
ORDER BY c.first_name, o.order_date;
 first_name | order_date | product  | last_product
------------+------------+----------+--------------
 Maria      | 2025-08-02 | Laptop   | Desk
 Maria      | 2025-08-11 | Keyboard | Desk
 Maria      | 2025-11-02 | Desk     | Desk
 Sofia      | 2025-08-19 | Desk     | Monitor
 Sofia      | 2025-10-10 | Monitor  | Monitor

An easier alternative: FIRST_VALUE(p.name) OVER (PARTITION BY o.customer_id ORDER BY o.order_date DESC) gives the latest product without touching the frame. PostgreSQL, MySQL, and SQLite also have NTH_VALUE(column, n) for the nth value; SQL Server doesn’t.

NTILE: Split Rows into Equal Groups

NTILE(n) divides the rows into n groups of (nearly) equal size and numbers them 1 to n. Split customers into three spending tiers:

WITH spend AS (
    SELECT c.first_name,
           SUM(o.quantity * p.price) AS total_spent
    FROM orders o
    JOIN customers c ON c.customer_id = o.customer_id
    JOIN products p  ON p.product_id = o.product_id
    WHERE o.status = 'shipped'
    GROUP BY c.customer_id, c.first_name
)
SELECT first_name,
       total_spent,
       NTILE(3) OVER (ORDER BY total_spent DESC) AS spend_group
FROM spend
ORDER BY total_spent DESC;
 first_name | total_spent | spend_group
------------+-------------+-------------
 Omar       |     1798.00 |           1
 Maria      |      989.00 |           1
 Kevin      |      720.00 |           2
 Sofia      |      569.00 |           2
 Ana        |      498.00 |           3
 James      |       75.00 |           3

Group 1 is the top third of spenders. NTILE(4) gives quartiles and NTILE(10) deciles, which is common in customer segmentation. When the rows don’t divide evenly, the first groups get one extra row each. And NTILE splits by position, not value: two customers with the same total can land in different groups.

PERCENT_RANK and CUME_DIST

These two place each row on a 0-to-1 scale:

  • PERCENT_RANK() is the share of other rows ranked below this one: 0 for the first, 1 for the last.
  • CUME_DIST() is the share of rows at or below this one.
SELECT name,
       price,
       ROUND(CAST(PERCENT_RANK() OVER (ORDER BY price) AS DECIMAL(5,4)), 2) AS pct_rank,
       ROUND(CAST(CUME_DIST()    OVER (ORDER BY price) AS DECIMAL(5,4)), 2) AS at_or_below
FROM products
ORDER BY price;
     name     | price  | pct_rank | at_or_below
--------------+--------+----------+-------------
 Mouse        |  25.00 |     0.00 |        0.17
 Keyboard     |  45.00 |     0.20 |        0.33
 Office Chair | 180.00 |     0.40 |        0.50
 Monitor      | 249.00 |     0.60 |        0.67
 Desk         | 320.00 |     0.80 |        0.83
 Laptop       | 899.00 |     1.00 |        1.00

Read the Monitor row as “60% of the other products are cheaper” and “67% of products cost this much or less.” The CAST to DECIMAL is there because these functions return floating-point numbers, and PostgreSQL’s two-argument ROUND only accepts decimals.

Percent of Total with an Aggregate Window

Any aggregate (SUM, AVG, COUNT, MIN, MAX) can be a window function. Combined with GROUP BY, it answers “what share of its category does each product bring in?”:

SELECT p.category,
       p.name,
       SUM(o.quantity * p.price) AS revenue,
       ROUND(100.0 * SUM(o.quantity * p.price)
             / SUM(SUM(o.quantity * p.price)) OVER (PARTITION BY p.category), 1) AS pct_of_category
FROM orders o
JOIN products p ON p.product_id = o.product_id
WHERE o.status = 'shipped'
GROUP BY p.category, p.name
ORDER BY p.category, revenue DESC;
  category   |     name     | revenue | pct_of_category
-------------+--------------+---------+-----------------
 Accessories | Keyboard     |   90.00 |            54.5
 Accessories | Mouse        |   75.00 |            45.5
 Electronics | Laptop       | 2697.00 |            78.3
 Electronics | Monitor      |  747.00 |            21.7
 Furniture   | Office Chair |  720.00 |            69.2
 Furniture   | Desk         |  320.00 |            30.8

SUM(SUM(...)) OVER (...) looks odd, but it reads in two steps: the inner SUM is the GROUP BY total for each product, and the outer SUM ... OVER (PARTITION BY category) adds up those product totals across the category. Window functions run after GROUP BY, so they can work on grouped results.

Naming a Window with the WINDOW Clause

When several functions use the same window, define it once with WINDOW and refer to it by name:

SELECT order_id,
       customer_id,
       order_date,
       ROW_NUMBER() OVER w AS order_number,
       LAG(order_date) OVER w AS previous_order
FROM orders
WHERE customer_id IN (1, 2)
WINDOW w AS (PARTITION BY customer_id ORDER BY order_date)
ORDER BY customer_id, order_date;
 order_id | customer_id | order_date | order_number | previous_order
----------+-------------+------------+--------------+----------------
      101 |           1 | 2025-08-02 |            1 |
      103 |           1 | 2025-08-11 |            2 | 2025-08-02
      112 |           1 | 2025-11-02 |            3 | 2025-08-11
      102 |           2 | 2025-08-05 |            1 |
      106 |           2 | 2025-09-07 |            2 | 2025-08-05

The WINDOW clause goes after WHERE/GROUP BY/HAVING and before ORDER BY. It works in PostgreSQL, MySQL 8, SQLite, and SQL Server 2022 or later with database compatibility level 160 (older SQL Server versions need the window written out each time).

Quick Reference

FunctionReturnsNeeds ORDER BY?
LAG(col, n, default)Value from n rows beforeYes
LEAD(col, n, default)Value from n rows afterYes
FIRST_VALUE(col)First value in the frameYes, in practice
LAST_VALUE(col)Last value in the frame (watch the default frame)Yes, in practice
NTH_VALUE(col, n)nth value (not in SQL Server)Yes, in practice
NTILE(n)Group number from 1 to nYes
PERCENT_RANK()Relative rank from 0 to 1Yes
CUME_DIST()Share of rows at or below, up to 1Yes
SUM/AVG/COUNT(...) OVERAggregate over the windowOptional

Common Mistakes to Avoid

  • Forgetting ORDER BY in OVER(). Without it, “previous” and “next” have no meaning.
  • Forgetting PARTITION BY. Without it, LAG compares a customer’s first order with the previous customer’s last order.
  • Trusting LAST_VALUE with the default frame. Add ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, or use FIRST_VALUE with a descending sort.
  • Filtering on a window function in WHERE. It doesn’t exist yet at that point. Use a CTE or subquery.
  • Comparing periods with gaps. LAG uses the previous row, not the previous month. Fill in missing months first.
  • Dividing by a previous value that could be zero or NULL. Use NULLIF(..., 0), and expect NULL for the first row.

Frequently Asked Questions

What is the difference between LAG and LEAD?

LAG reads a value from an earlier row in the window; LEAD reads from a later row. Both use the window’s ORDER BY to decide what “earlier” and “later” mean.

How do I calculate month-over-month growth in SQL?

Total each month in a CTE, then use LAG(revenue) OVER (ORDER BY month) to get the previous month’s value, and compute 100.0 * (revenue - previous) / previous.

Why does LAST_VALUE return the current row?

Because with ORDER BY, the default frame ends at the current row. Extend it with ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.

Can I use LAG without a self join?

Yes, that’s the point. Before window functions, comparing a row with the previous one needed a self join with a correlated condition; LAG does it in one pass and is much faster.

Conclusion

LAG and LEAD compare each row with its neighbors, which makes month-over-month changes, time between events, and “latest record” queries short and fast. FIRST_VALUE and LAST_VALUE pick values from the ends of a window (mind the frame), NTILE splits rows into tiers, PERCENT_RANK and CUME_DIST place rows on a 0-to-1 scale, and aggregates with OVER give percent-of-total without a second query.

Next in the Learn SQL series, you’ll put these tools to work on real-world messy data in Cleaning Messy Data with Pure SQL.