11/34
Part 3 of 6 · LAG and datesLearn and do
Sort by the date, not the id, because ids can be out of date order
The window sorts by the date and uses the id only to break ties within a date. Sort by the id alone, and user 1 travels back in time:
SELECT user_id, order_id, ordered_on,
LAG(ordered_on) OVER w AS prev_on,
julianday(ordered_on) - julianday(LAG(ordered_on) OVER w) AS gap_days
FROM orders
WINDOW w AS (PARTITION BY user_id ORDER BY order_id)
ORDER BY user_id, order_id;
| user_id | order_id | ordered_on | prev_on | gap_days |
|---|---|---|---|---|
| 1 | 1 | 2026-03-01 | NULL | NULL |
| 1 | 3 | 2026-03-03 | 2026-03-01 | 2.0 |
| 1 | 6 | 2026-03-02 | 2026-03-03 | -1.0 |
| 2 | 2 | 2026-03-01 | NULL | NULL |
| 2 | 5 | 2026-03-09 | 2026-03-01 | 8.0 |
| 3 | 4 | 2026-03-03 | NULL | NULL |
| 4 | 7 | 2026-03-10 | NULL | NULL |
User 1's three orders, in the two orders the windows used:
| ORDER BY order_id | Gap | ORDER BY ordered_on, order_id | Gap |
|---|---|---|---|
| #1, 03-01 | #1, 03-01 | ||
| #3, 03-03 | 2.0 | #6, 03-02 | 1.0 |
| #6, 03-02 | -1.0, backwards | #3, 03-03 | 1.0 |
Order 6 was written after order 3, but it happened the day before. An id follows the order rows were inserted in, not the order events happened in. Backfills and late-arriving data pull the two apart. Order by the event's date.
In the editor, write PREVIOUS_ORDER: each order's previous order, by date.