What do LAG and LEAD do?
LAG returns the value from the previous row of the window and LEAD from the next, so a row can be compared with its neighbour within a group. ORDER BY inside OVER defines previous and next, PARTITION BY the groups. In a group's first row LAG gives NULL unless a third argument sets a default. Filtering by the result is done in a CTE.
SQL · Window functions
Two identical transactions three seconds apart. How to find such pairs with one query?
A user pressed a button twice and the account got two identical payments three seconds apart. Among a million transactions such pairs cannot be found by hand. For that you have to compare a row with the previous one within the same account, and this is exactly how LAG and LEAD work.
How it works and why. LAG(col) returns the column value from the previous row of the window, LEAD(col) from the next one. "Previous" and "next" are defined by the same ORDER BY inside OVER, and the group boundaries by PARTITION BY. The second argument sets the offset (1 by default), the third the value substituted if there is no such row:
-- LAG(expr, offset, default)
LAG(amount) OVER w -- the previous row, NULL in the first
LAG(amount, 2) OVER w -- two rows back
LAG(amount, 1, 0) OVER w -- instead of NULL in the first row there is 0
LEAD(status) OVER w -- the next row
In the first row of each group there is no previous one, so LAG gives NULL (for LEAD the same in the last row). This is not an error but the norm. A difference with NULL is NULL too, and a comparison condition drops it. The sample data: transactions of account 10.
What LAG sees
| id | time | amount |
|---|---|---|
| 1 | 10:00:00 | 100 |
| 2 | 10:00:03 | 100 |
| 3 | 10:10:00 | 300 |
| id | amount | prev_amount | gap |
|---|---|---|---|
| 1 | 100 | NULL | NULL |
| 2 | 100 | 100 | 00:00:03 |
| 3 | 300 | 100 | 00:09:57 |
-- the gap between consecutive transactions of an account
SELECT id, amount,
LAG(amount) OVER w AS prev_amount,
created_at - LAG(created_at) OVER w AS gap
FROM transactions
WHERE account_id = 10
WINDOW w AS (PARTITION BY account_id ORDER BY created_at, id);
Row 2 has the same amount as the previous one and a three-second gap: a candidate for a double submit. This is the sign the next query looks for. Filtering by the value of a window function needs a CTE because it cannot go in WHERE:
-- double submit: the same amount within 5 seconds; result id 2
WITH g AS (
SELECT id, account_id, amount, created_at,
LAG(amount) OVER w AS prev_amount,
LAG(created_at) OVER w AS prev_at
FROM transactions
WINDOW w AS (PARTITION BY account_id ORDER BY created_at, id)
)
SELECT id, account_id, amount
FROM g
WHERE amount = prev_amount
AND created_at - prev_at < INTERVAL '5 seconds';
The result: the transaction with id 2. Pairs from different accounts do not mix because PARTITION BY account_id limits the window to one account. The second key id in ORDER BY is needed so that on equal time the order is unambiguous.
Another example: a sequence of statuses. LEAD lets you look forward, for example to find orders that skipped an allowed transition:
-- order status changes: each row together with the next status
SELECT order_id, status, changed_at,
LEAD(status) OVER (PARTITION BY order_id ORDER BY changed_at, id) AS next_status
FROM order_status_log;
Now every row has a pair "status and next status", easy to compare with a table of allowed transitions.
With a window and without one
LAG without PARTITION BY
The previous row is a row of another account. At group boundaries foreign transactions are compared.
PARTITION BY account_id ORDER BY …
The previous is taken only within the account, the first row of a group gets NULL.
Limits and alternatives. LAG and LEAD do not depend on the window frame: they always take the row at the offset in the ordered group. Without ORDER BY in OVER the "previous" row is undefined. Instead of the functions you can do a self join on t2.created_at < t1.created_at, but it is more complex and slower, and the result needs extra filtering. To compare not with the neighbour but with the nearest row meeting a condition, other tools are needed. If a double submit is defined by an idempotency key rather than by time, a GROUP BY with HAVING COUNT(*) > 1 is enough.
Typical mistakes.
- No
PARTITION BY: the "previous" row belongs to another group. - No
ORDER BYor a non-unique key: the previous row is undefined, the result unstable. - Ignoring NULL in the first row of a group: a filter without a check drops it silently, or arithmetic with it yields NULL.
LAGinWHERE: an error, a CTE is needed.- Comparing timestamps as strings instead of
timestamp: the interval is computed wrongly.
Check yourself
What does LAG(amount) return for the first row of each account and how do you get 0 instead?
Answer
NULL because there is no previous row in the group. The third argument sets a default value: LAG(amount, 1, 0) returns 0.
Why does the query for finding double payments need both PARTITION BY account_id and a CTE?
Answer
PARTITION BY stops transactions of different accounts from being compared: the previous row is taken only within its own account. A CTE is needed because the result of LAG cannot be used in the WHERE of the same query where it is computed.