Reading history

SQL LAG and LEAD: Compare Rows

5 min read 0 views

Use SQL LAG and LEAD to compare each row with the previous or next one: month-over-month change, percentage growth, days between orders and FIRST_VALUE.

Reports often compare a row with the one before it: “How much did sales grow since last month?” or “How many days passed between a customer’s orders?” Before window functions, this needed an awkward self join. Now LAG and LEAD fetch a value from the previous or next row directly, so month-over-month changes take one short query.

In this lesson you will learn

  • How LAG and LEAD read neighbouring rows
  • Calculating change and percentage change
  • Using PARTITION BY to compare within each customer
  • Offsets and default values
  • FIRST_VALUE and LAST_VALUE

You should know window functions and date functions.

LAG and LEAD

LAG(column) returns the value from the previous row and LEAD(column) from the next row, in the order given by OVER (ORDER BY …).

CREATE TABLE monthly_sales (month TEXT, revenue INTEGER);
INSERT INTO monthly_sales VALUES
 ('2026-01', 42000), ('2026-02', 47500), ('2026-03', 45100),
 ('2026-04', 51800), ('2026-05', 51800), ('2026-06', 60200);

SELECT month,
       revenue,
       LAG(revenue) OVER (ORDER BY month)            AS prev_month,
       revenue - LAG(revenue) OVER (ORDER BY month)  AS change,
       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
             / LAG(revenue) OVER (ORDER BY month), 1) AS pct_change,
       LEAD(revenue) OVER (ORDER BY month)           AS next_month
FROM monthly_sales;

Output

+---------+---------+------------+--------+------------+------------+
| month   | revenue | prev_month | change | pct_change | next_month |
+---------+---------+------------+--------+------------+------------+
| 2026-01 | 42000   | NULL       | NULL   | NULL       | 47500      |
| 2026-02 | 47500   | 42000      | 5500   | 13.1       | 45100      |
| 2026-03 | 45100   | 47500      | -2400  | -5.1       | 51800      |
| 2026-04 | 51800   | 45100      | 6700   | 14.9       | 51800      |
| 2026-05 | 51800   | 51800      | 0      | 0.0        | 60200      |
| 2026-06 | 60200   | 51800      | 8400   | 16.2       | NULL       |
+---------+---------+------------+--------+------------+------------+
(6 rows)
  • January has no previous month, so prev_month is NULL and so are the change columns. June has no next month.
  • Change = this month − last month. March fell by 2,400; May stayed level.
  • Percentage change = change ÷ last month × 100. Writing 100.0 forces decimal division, giving 13.1% for February.

Comparing Within Groups

Add PARTITION BY so each customer is compared only with their own earlier orders.

-- Days between each customer's orders, and their first order amount
SELECT customer,
       order_date,
       amount,
       julianday(order_date)
         - julianday(LAG(order_date) OVER (PARTITION BY customer ORDER BY order_date)) AS days_since_last,
       FIRST_VALUE(amount) OVER (PARTITION BY customer ORDER BY order_date) AS first_amount
FROM orders
WHERE status <> 'cancelled'
ORDER BY customer, order_date;

Output

+----------+------------+--------+-----------------+--------------+
| customer | order_date | amount | days_since_last | first_amount |
+----------+------------+--------+-----------------+--------------+
| Joya     | 2026-02-14 | 2300   | NULL            | 2300         |
| Joya     | 2026-03-21 | 300    | 35.0            | 2300         |
| Karim    | 2026-01-05 | 1200   | NULL            | 1200         |
| Karim    | 2026-03-09 | 1500   | 63.0            | 1200         |
| Rina     | 2026-01-18 | 450    | NULL            | 450          |
| Rina     | 2026-02-27 | 650    | 40.0            | 450          |
| Tuhin    | 2026-03-30 | NULL   | NULL            | NULL         |
+----------+------------+--------+-----------------+--------------+
(7 rows)
  • Each customer’s first order has no previous order, so days_since_last is NULL.
  • julianday turns dates into day numbers, so subtracting gives days between orders. Karim waited 63 days because his cancelled February order is filtered out.
  • FIRST_VALUE(amount) repeats each customer’s first order amount on every row, useful for “compared with their first purchase” reports.

Offsets and Defaults

Both functions take two optional arguments: LAG(column, offset, default).

LAG(revenue, 3) OVER (ORDER BY month)      -- value 3 rows back (same month last quarter)
LAG(revenue, 1, 0) OVER (ORDER BY month)   -- 0 instead of NULL for the first row

Be careful with defaults: a previous revenue of 0 would make a percentage change divide by zero, so NULL is often the more honest answer.

LAST_VALUE needs a full frame to see the last row of the group, because the default frame stops at the current row: LAST_VALUE(x) OVER (PARTITION BY g ORDER BY d ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING).

Common Mistakes

  1. Forgetting ORDER BY inside OVER. Without it, “previous row” has no meaning.
  2. Integer division in percentages. 100 * change / prev on integers can round away the decimals; use 100.0.
  3. Missing months. If April has no row, LAG compares May with March. Fill gaps with a calendar first.
  4. Filtering with WHERE on a window result. Window values are computed after WHERE; wrap the query in a subquery or CTE to filter them.

Practice Exercises

Exercise 1. List employees from highest to lowest salary, with how much less each earns than the person just above.

Show answer
SELECT name, salary,
       LAG(salary) OVER (ORDER BY salary DESC) - salary AS gap_to_next_higher
FROM employees
ORDER BY salary DESC;

The biggest gap is 75,000, between Lipi (170,000) and Mou (95,000).

Exercise 2. In monthly_sales, show only the months where revenue fell.

Show answer
SELECT month, revenue, change
FROM (SELECT month, revenue,
             revenue - LAG(revenue) OVER (ORDER BY month) AS change
      FROM monthly_sales)
WHERE change < 0;

Only March 2026, with a change of −2400.

Frequently Asked Questions

Can I use LAG in older MySQL versions?

Window functions arrived in MySQL 8.0 and SQLite 3.25. In older versions, use a self join that matches each row with the row for the previous period.

What is the difference between LAG and a self join?

Both can compare rows, but LAG reads the neighbour in one pass and needs no join condition. A self join must describe how to find the previous row, which is harder when periods are irregular.

Summary

  • LAG reads the previous row and LEAD the next, in the window’s order.
  • Change = current − previous; percentage change = change ÷ previous × 100.0.
  • PARTITION BY restarts the comparison for each group.
  • The first row of each group gets NULL unless you give a default.

Next: Running Totals and Moving Averages in SQL.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *