Sub topic 3
Looking ahead with LEAD
This chapter assumes you know basic SELECT, WHERE, and ORDER BY, can write an OVER clause with PARTITION BY and ORDER BY, and understand LAG, which reads a value from an earlier row.
Looking ahead with LEAD
LEAD returns a value from a later row in the same ordered window. It is the mirror image of LAG.
SELECT sales_month,
amount,
LEAD(amount) OVER (ORDER BY sales_month) AS next_amount
FROM monthly_sales
ORDER BY sales_month;The last row returns NULL because no later row exists.
Offset and default arguments
The second argument is the offset, the number of rows to move forward. It defaults to 1. The third argument is the default value, returned when the offset moves past the end of the partition instead of NULL.
SELECT sales_month,
amount,
LEAD(amount, 1, 0) OVER (ORDER BY sales_month) AS next_amount
FROM monthly_sales
ORDER BY sales_month;Here the last row returns 0 instead of NULL.
Calculating period-over-period change
Subtract the previous period's value from the current value to get the change.
SELECT sales_month,
amount,
amount - LAG(amount) OVER (ORDER BY sales_month) AS change_from_prev
FROM monthly_sales
ORDER BY sales_month;The first row returns NULL because it has no previous month.
Removing duplicate rows with ROW_NUMBER
Number the rows within each duplicate group, then delete every row after the first. Run the inner SELECT alone first to check which rows will be removed, and back up the table before you run the DELETE.
DELETE FROM customers
WHERE rowid IN (
SELECT rid
FROM (
SELECT rowid AS rid,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY created_at, customer_id
) AS rn
FROM customers
)
WHERE rn > 1
);Skipping NULLs with IGNORE NULLS
IGNORE NULLS makes LAG or LEAD skip NULL values and return the nearest non-NULL value in the given direction.
SELECT reading_time,
reading,
LAG(reading) IGNORE NULLS OVER (ORDER BY reading_time) AS last_known_reading
FROM sensor_readings
ORDER BY reading_time;Performance considerations
Each window needs its rows sorted by the PARTITION BY and ORDER BY columns. Windows with identical definitions can share one sort. Large sorts use memory and temporary space, so check the execution plan on big tables. Filtering on a ROW_NUMBER result requires an inline view, because the database must compute the numbers before it can filter.
Exercise
Using monthly_sales, how would you return each month's amount alongside the next month's amount, showing 0 for the last month?
Show answer
Use LEAD(amount, 1, 0) OVER (ORDER BY sales_month). The default argument 0 replaces the NULL that would otherwise appear in the last row.