LAG and LEAD read earlier and later rows in the window's order
Some questions compare a row with the one before it.
What does LAG(ordered_on) return on a user's first order?
Each user's previous and next order date:
SELECT user_id, order_id, ordered_on,
LAG(ordered_on) OVER w AS prev_on,
LEAD(ordered_on) OVER w AS next_on
FROM orders
WINDOW w AS (PARTITION BY user_id ORDER BY ordered_on, order_id)
ORDER BY user_id, ordered_on, order_id;| user_id | order_id | ordered_on | prev_on | next_on |
|---|---|---|---|---|
| 1 | 1 | 2026-03-01 | NULL | 2026-03-02 |
| 1 | 6 | 2026-03-02 | 2026-03-01 | 2026-03-03 |
| 1 | 3 | 2026-03-03 | 2026-03-02 | NULL |
| 2 | 2 | 2026-03-01 | NULL | 2026-03-09 |
| 2 | 5 | 2026-03-09 | 2026-03-01 | NULL |
| 3 | 4 | 2026-03-03 | NULL | NULL |
| 4 | 7 | 2026-03-10 | NULL | NULL |
For order 6, LAG and LEAD look one row up and one row down inside user 1's partition:
| User 1's partition, by date | For order 6 | |
|---|---|---|
| #1 | 2026-03-01 | LAG(ordered_on) reads this row |
| #6 | 2026-03-02 | the current row |
| #3 | 2026-03-03 | LEAD(ordered_on) reads this row |
Then the partition ends.
LAG reads a value from an earlier row in the partition, and LEAD from a later one, in the window's order. LAG(x) is the previous row's x, and LAG(x, 2) the one before that.
When that row doesn't exist, they return NULL, or the third argument if you give one. LAG(x, 1, 0) returns 0 on the first row. Order 1 has no row above it, so its LAG is NULL. Order 3 has none below it, so its LEAD is NULL.
WINDOW w AS (...) names the window once, so both calls share it.
To turn two dates into days, subtract their day numbers: julianday(d) turns a date into a day number, so julianday(later) - julianday(earlier) is the days between them. A later step shows why you can't subtract the dates themselves.
In the editor, write GAP_DAYS: the days since each user's previous order.
- 1
Write
GAP_DAYS: every order withuser_id, order_id, ordered_onandgap, the whole days since the same user's previous order, NULL on their first. - 2
Read the previous date with LAG over each user's orders in date order,
order_idbreaking ties, and subtractjulianday()values.
Run your code to check it. Output shows here.