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_idorder_idordered_onprev_ongap_days
112026-03-01NULLNULL
132026-03-032026-03-012.0
162026-03-022026-03-03-1.0
222026-03-01NULLNULL
252026-03-092026-03-018.0
342026-03-03NULLNULL
472026-03-10NULLNULL

User 1's three orders, in the two orders the windows used:

ORDER BY order_idGapORDER BY ordered_on, order_idGap
#1, 03-01#1, 03-01
#3, 03-032.0#6, 03-021.0
#6, 03-02-1.0, backwards#3, 03-031.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.