Consecutive Funnel Steps With LAG
Count consecutive funnel conversions with LAG(event, n) over user-ordered events: a step only counts when its predecessor steps happened.
Code
-- 连续漏斗:cart 的前一条事件必须是 view,checkout 的前两条必须是 view→cart
-- 只看同用户按时间排序后的事件流;乱序或漏步的用户不计入
WITH ordered AS (
SELECT
user_id,
event,
LAG(event, 1) OVER (PARTITION BY user_id ORDER BY ts, event) AS prev1,
LAG(event, 2) OVER (PARTITION BY user_id ORDER BY ts, event) AS prev2
FROM funnel_events
WHERE event IN ('view', 'cart', 'checkout', 'purchase')
)
SELECT
COUNT(*) FILTER (WHERE event = 'view') AS viewed,
COUNT(*) FILTER (WHERE event = 'cart'
AND prev1 = 'view') AS view_to_cart,
COUNT(*) FILTER (WHERE event = 'checkout'
AND prev1 = 'cart' AND prev2 = 'view') AS cart_to_checkout,
COUNT(*) FILTER (WHERE event = 'purchase'
AND prev1 = 'checkout' AND prev2 = 'cart') AS checkout_to_purchase
FROM ordered;Inside the snippet
What runs is SELECT, with funnel_events and ordered as the object involved.
Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause narrowing which rows one statement affects; COUNT aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
Watch out for
- Window functions evaluate after
WHERE/GROUP BY, so filtering on their output in the same-levelWHEREwill not work — use an outer query or a CTE.
Putting it to use
The funnel_events table is the working surface here.
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Name the tables involved in this file.
- `funnel_events`, `ordered` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.