Window functions you will actually use in pipelines
Four window patterns cover almost every pipeline need: latest-row dedupe, sessionization, running totals and gap detection — with the performance traps of each.
TL;DR
- 90% of pipeline window use is four patterns: latest row per key, sessionize, running total, find gaps.
- Every window with
PARTITION BYshuffles on that key — a skewed key skews the whole stage. - A window without
PARTITION BYsends everything to one task. On big data that is an outage, not a query.
Pattern 1 — latest row per key
The workhorse of every bronze-to-silver step:
WITH ranked AS (
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY order_id
ORDER BY updated_at DESC, _ingest_seq DESC
) AS rn
FROM bronze.orders_cdc
)
SELECT * FROM ranked WHERE rn = 1;Use ROW_NUMBER, not RANK — RANK returns ties and your dedupe stops deduping. Always add a deterministic tie-breaker column.
Pattern 2 — sessionize events
Mark a new session when the gap from the previous event exceeds a threshold, then cumulatively sum the markers:
WITH gaps AS (
SELECT *,
CASE WHEN ts - LAG(ts) OVER (PARTITION BY user_id ORDER BY ts)
> INTERVAL 30 MINUTES
THEN 1 ELSE 0 END AS new_session
FROM events
)
SELECT *,
SUM(new_session) OVER (
PARTITION BY user_id ORDER BY ts
ROWS UNBOUNDED PRECEDING
) AS session_id
FROM gaps;Pattern 3 — running totals
SELECT order_date,
SUM(amount) OVER (
PARTITION BY store_id ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_revenue
FROM gold.daily_sales;Spell out the frame. The default frame with ORDER BY is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, and RANGE treats ties as one group — subtly different sums, and slower.
Pattern 4 — find gaps in sequences
SELECT user_id, ts AS gap_starts_after,
next_ts AS resumes_at
FROM (
SELECT user_id, ts,
LEAD(ts) OVER (PARTITION BY user_id ORDER BY ts) AS next_ts
FROM heartbeats
)
WHERE next_ts - ts > INTERVAL 5 MINUTES;Performance notes
- One stage can evaluate multiple window functions only if they share the same
PARTITION BYandORDER BY. Group your windows accordingly. - Check the plan for a single-partition
Windownode (Exchange SinglePartitionabove it) — that's the no-PARTITION BYtrap. - Pre-filter before the window. A
WHEREafter the window still pays for the full shuffle.
Practice
Further reading
Keep going
Deduplicate a raw events table
Keep exactly one row per event_id — the latest by timestamp — from a bronze table that receives replays and retries.
Sessionize clickstream with window functions
Group raw page views into sessions using a 30-minute inactivity gap, with pure SQL window functions.
Delta Lake MERGE without the full-table rewrite
Why MERGE quietly rewrites far more data than it changes, and the three fixes that keep it fast: prune the target, deduplicate the source, compact after.
One practical note a week
Get new articles, problems and guides in your inbox.
Thanks! You're on the list. (Local demo — no email provider is wired up yet.)