Sub topic 7
Looking at Neighbouring Rows with LAG and LEAD
This chapter assumes you know SELECT, ORDER BY, aggregate functions, and common table expressions (CTEs). It also assumes your database supports window functions, such as PostgreSQL, MySQL 8+, SQL Server, SQLite 3.25+, or Oracle.
What LAG and LEAD do
LAG is a window function that reads a value from an earlier row. LEAD reads a value from a later row. Both keep the current row in the result.
This makes them useful for questions such as:
- How much did revenue change from the previous month?
- What sale came next for each customer?
- How long was the gap between two events?
- Did a value increase or decrease compared with its neighbour?
The rows are “previous” or “next” only after the window's ORDER BY defines their order.
SELECT
sale_month,
revenue,
LAG(revenue) OVER (ORDER BY sale_month) AS previous_revenue,
LEAD(revenue) OVER (ORDER BY sale_month) AS next_revenue
FROM monthly_revenue
ORDER BY sale_month;For the first month, LAG returns NULL because there is no earlier row. For the last month, LEAD returns NULL because there is no later row.
Comparing a row with the previous row
You can use an expression around LAG to calculate a change.
SELECT
sale_month,
revenue,
LAG(revenue) OVER (ORDER BY sale_month) AS previous_revenue,
revenue - LAG(revenue) OVER (ORDER BY sale_month) AS change_from_previous,
revenue * 100.0
/ NULLIF(LAG(revenue) OVER (ORDER BY sale_month), 0)
- 100 AS percent_change
FROM monthly_revenue
ORDER BY sale_month;NULLIF prevents division by zero. The first row still has a NULL percentage because it has no previous revenue.
A repeated window expression is valid, but a CTE can make a longer calculation easier to read:
WITH compared AS (
SELECT
sale_month,
revenue,
LAG(revenue) OVER (ORDER BY sale_month) AS previous_revenue
FROM monthly_revenue
)
SELECT
sale_month,
revenue,
previous_revenue,
revenue - previous_revenue AS change_from_previous
FROM compared
ORDER BY sale_month;Comparing rows within each group
Add PARTITION BY when each entity needs its own sequence. The function then does not compare one customer's row with another customer's row.
SELECT
customer_id,
sale_date,
amount,
LAG(amount) OVER (
PARTITION BY customer_id
ORDER BY sale_date, id
) AS previous_amount,
LEAD(amount) OVER (
PARTITION BY customer_id
ORDER BY sale_date, id
) AS next_amount
FROM sales
ORDER BY customer_id, sale_date, id;Here, id breaks ties when a customer has multiple sales on the same date. A deterministic order is important because otherwise the database may choose different neighbouring rows between executions.
Offsets and default values
The second argument sets how many rows away to look. The optional third argument replaces the usual NULL when no row exists.
SELECT
sale_month,
revenue,
LAG(revenue, 2, 0) OVER (ORDER BY sale_month) AS revenue_two_months_ago,
LEAD(revenue, 1, 0) OVER (ORDER BY sale_month) AS next_revenue_or_zero
FROM monthly_revenue
ORDER BY sale_month;The value 0 is used only when the requested row is outside the window. It does not replace a real row whose revenue is itself NULL.
Exercise
Write a query that returns each employee's hire date and the next employee hired in the same department.
Show answer
SELECT employeeid, departmentid, hiredate, LEAD(hiredate) OVER (PARTITION BY departmentid ORDER BY hiredate, employeeid) AS nexthire_date FROM employees;