Window Functions Part 3: practice questions
400 questions in four levels, all on RetailMart, the practice database of this course. Write every query yourself, get it wrong, read the error, fix it. That is how it sticks.
Answers are coming soon. Post your query in the WhatsApp Community or Discord and we will check it together.
Easy 100 questions Medium 100 questions Hard 100 questions Crazy 100 questions
Core syntax, applied directly
CONCEPTUAL Q1 What does LAG(x) return for a given row? Q2 What does LEAD(x) return for a given row? Q3 Why do LAG/LEAD require an ORDER BY inside OVER()? Q4 What does LAG(x, 2) return (offset)? Q5 What does LAG(x, 1, 0) do (default for the first row)? Q6 What value does LAG return for the first row of a partition with no default? Q7 How does PARTITION BY change LAG/LEAD (reset per group)? Q8 Write the formula for month-over-month growth % using LAG. Q9 Why guard the LAG denominator with NULLIF in a growth %? Q10 Difference between LAG and accessing the previous row via a self-join. Q11 What is "period-over-period" analysis? Q12 How to compute the gap (days) between consecutive orders per customer. Q13 Can LAG/LEAD appear in WHERE directly? What's the workaround? Q14 How does LEAD(x, 1) help compute "time to next event"? Q15 Why must the ORDER BY be deterministic for LAG/LEAD to be meaningful? Q16 What's the result type of LAG on a numeric column? Q17 How to detect a change (current <> previous) with LAG. Q18 How to flag rows where value increased vs the previous row. Q19 Why might LAG over months need a gap-filled month series first? Q20 How to compute first-vs-second order delta with LAG. Q21 What does LEAD return for the last row of a partition (no default)? Q22 How to compute a running difference (delta) series with LAG. Q23 When to use LAG vs a window frame for "previous value". Q24 How to compute % change vs the same month last year (LAG 12 on monthly series). Q25 Name one analyst use each for LAG, LEAD, and period-over-period growth. LAG BASICS Q26 For each order per customer, show the previous order's net_total (LAG). Q27 For each order per customer, show the previous order_date. Q28 Monthly revenue with the previous month's revenue beside it. Q29 For each product price-ordered, the previous product's price. Q30 For each review per product, the previous review's rating. Q31 For each call per agent, the previous call's duration. Q32 For each shipment per courier, the previous delivery time. Q33 For each pay_slip per employee, the previous month's net_salary. Q34 For each order per store (by date), the previous order's value. Q35 LAG with offset 2: the order two-before per customer. Q36 LAG with default 0: previous net_total, 0 for first order. Q37 Monthly signups with previous month's signups. Q38 For each snapshot per (warehouse, product), the previous quantity. Q39 For each customer's order, the date of their previous order. Q40 Previous day's revenue beside each day's revenue. Q41 For each ad spend per campaign, the previous spend amount. Q42 For each ticket per agent, the previous ticket's created_date. Q43 For each product per brand (price desc), the next-cheaper price (LAG on desc). Q44 Previous week's order count beside each week. Q45 For each member, the previous points_balance snapshot (if ordered by date). Q46 LAG to show "prior status" of orders per customer over time. Q47 Previous quarter revenue beside each quarter. Q48 For each order line, the previous line's net_amount within the order. Q49 Previous month's expenses per department. Q50 For each customer, previous order value AND the one before (LAG 1 and LAG 2). LEAD BASICS Q51 For each order per customer, the NEXT order's net_total (LEAD). Q52 For each order per customer, the next order_date. Q53 Days until the next order per customer (LEAD on order_date - order_date). Q54 For each review per product, the next review's rating. Q55 For each call per customer, time until the next call. Q56 Monthly revenue with the next month's revenue beside it. Q57 For each product price-ordered, the next product's price. Q58 For each shipment per courier, the next shipment's shipped_date. Q59 LEAD with offset 2: the order two-after per customer. Q60 LEAD with default: next net_total, NULL->0 for the last order. Q61 For each page_view per session, the next view_timestamp (session step). Q62 For each pay_slip per employee, the next month's net_salary. Q63 Time gap to next ticket per agent. Q64 For each snapshot per product, the next day's quantity. Q65 For each customer's first order, when their second order happened (LEAD). Q66 Next week's order count beside each week. Q67 For each order per store, the next order's value. Q68 Gap to next review per customer (engagement cadence). Q69 For each campaign spend, the next spend amount and date. Q70 Next quarter revenue beside each quarter. Q71 For each member, the next points snapshot. Q72 Time until next purchase per customer (churn signal). Q73 For each order line, the next line's net_amount within the order. Q74 Next day's revenue beside each day. Q75 For each customer, next order value AND the one after (LEAD 1 and LEAD 2). DELTAS & PERIOD-OVER-PERIOD Q76 Month-over-month revenue growth % (LAG, NULLIF-guarded). Q77 Day-over-day change in order count. Q78 Gap in days between consecutive orders per customer. Q79 First-vs-second order value delta per customer. Q80 Detect price changes: rows where current price <> previous (price-ordered series). Q81 Flag days where revenue > previous day by > 20%. Q82 Week-over-week order growth % per store. Q83 Quarter-over-quarter revenue change per region. Q84 Change in net_salary vs previous month per employee. Q85 Delta in points_balance vs previous snapshot per member. Q86 Month-over-month signup growth %. Q87 Difference in delivery time vs previous shipment per courier. Q88 Web session duration: last view_timestamp - first via LEAD per session. Q89 Same-month-last-year revenue compare (LAG 12 on monthly series). Q90 Flag rating drops: review rating < previous review rating per product. Q91 Detect stock-outs: snapshot quantity drops to 0 from a positive previous. Q92 Order value delta vs previous order per customer (absolute + %). Q93 Month-over-month expense change % per department. Q94 Days between first and second order per customer (LEAD on first). Q95 Flag months with negative MoM growth. Q96 Consecutive-day revenue streak setup (current vs previous comparison). Q97 Detect a >50% price jump vs previous (data-entry error flag). Q98 Customer reactivation gap: longest gap between consecutive orders. Q99 Period-over-period contribution: this month vs last month per category. Q100 MoM revenue table per store: revenue, prev_revenue, growth %, up/down flag. Combined ideas, multi-step thinking
CONCEPTUAL Q1 Why partition before LAG for "previous order per customer"? Q2 Growth % formula with LAG; why NULLIF guards division. Q3 Why a gap-filled month series matters before LAG on monthly data. Q4 LAG(x, n, default) - each argument's role. Q5 How to compute "days since previous order" per customer. Q6 How to detect a change-point (value differs from previous). Q7 Sessionization idea: new session when gap to previous event > N minutes. Q8 Why LEAD is natural for "time-to-next-event". Q9 YoY compare: LAG 12 on a monthly series - requirements. Q10 How to flag the first row of each partition (LAG IS NULL). Q11 Compute both prior and next value in one query (LAG + LEAD). Q12 Why filter on a LAG result must be in an outer query/CTE. Q13 How to compute a delta and a % delta together. Q14 Detecting streaks: same value as previous row (run-length idea). Q15 Why deterministic ORDER BY (date, id) is needed for stable LAG. Q16 Difference: gap to previous vs gap to next event. Q17 How to handle missing periods (no order in a month) for growth. Q18 Compute "previous non-null value" - limitation of plain LAG. Q19 How to compute moving change (this - 3 rows ago) with LAG offset. Q20 Sessionization: cumulative sum of "new session" flags = session id. Q21 Why period-over-period needs aggregation to a grain first. Q22 How to compute first-purchase to second-purchase latency. Q23 Detect reactivations: gap to previous order > 90 days. Q24 How to compare each region's month to its own previous month. Q25 When LAG/LEAD beats a self-join (clarity + speed). PERIOD-OVER-PERIOD Q26 MoM revenue growth % per store (aggregate to month, LAG). Q27 WoW order-count growth % per store. Q28 QoQ revenue change per region. Q29 YoY monthly revenue compare (LAG 12). Q30 MoM signup growth % per region. Q31 MoM expense change % per department. Q32 Day-over-day revenue change (company-wide, gap-filled). Q33 MoM net_salary change per employee. Q34 MoM units-sold growth % per product. Q35 Week-over-week active customers change. Q36 MoM revenue growth % per category. Q37 QoQ growth per store with up/down flag. Q38 MoM refund change % per category. Q39 MoM ad-spend change % per platform. Q40 YoY quarterly revenue compare per region. Q41 MoM review-count change per product. Q42 MoM ticket-volume change per category. Q43 MoM page-views change per device. Q44 MoM AOV (avg order value) change per store. Q45 MoM new-customer growth per city (via addresses). Q46 MoM revenue contribution change per region (% of company). Q47 MoM growth flagged where it turns negative. Q48 Rolling 2-period change: this month vs 2 months ago (LAG 2). Q49 MoM growth for the top-5 brands by revenue. Q50 Build a MoM table per store: month, revenue, prev, growth %, flag. GAP ANALYSIS Q51 Days between consecutive orders per customer. Q52 Average inter-order gap per customer (LAG then AVG). Q53 Longest gap between orders per customer. Q54 Customers with a gap > 90 days (reactivation candidates). Q55 Time to second order per customer (first->second latency). Q56 Gap to next review per customer (engagement cadence). Q57 Time between consecutive calls per customer. Q58 Gap between consecutive shipments per courier. Q59 Days between consecutive snapshots per (warehouse, product). Q60 Time between first and last order per customer (lifespan). Q61 Gap between consecutive logins/page-views per session. Q62 Customers whose most recent gap exceeds their average gap (slowing down). Q63 Inter-purchase time distribution buckets per customer. Q64 Gap to next ticket per agent (workload spacing). Q65 Days since previous price change per product (price-ordered). Q66 Gap between consecutive payments per order. Q67 Median inter-order gap per region (LAG then percentile). Q68 Customers with shrinking gaps (accelerating purchase frequency). Q69 First-order to registration latency (orders vs registration_date). Q70 Gap between consecutive promotions (start dates). Q71 Time-to-next-order after a return (post-return behavior). Q72 Largest single-day revenue jump per store (gap to previous day). Q73 Customers dormant > 180 days (gap to today via LEAD/CURRENT_DATE). Q74 Average gap between reviews per product. Q75 Build a per-customer "purchase cadence" table: avg/min/max gap. SESSIONIZATION & CHANGE DETECTION Q76 Flag a new web session when gap to previous view > 30 minutes. Q77 Assign session ids via cumulative sum of new-session flags. Q78 Session duration per session (first to last view_timestamp). Q79 Views per session (count within derived session id). Q80 Detect price changes: rows where price <> previous price per product. Q81 Detect > 50% price jumps (likely data-entry errors). Q82 Detect order-status transitions over time per order (if status changes logged). Q83 Detect tier upgrades/downgrades per customer over time. Q84 Detect stock-outs: quantity drops to 0 from positive previous. Q85 Detect rating drops vs previous review per product. Q86 Flag revenue days that broke the previous record (running-max compare). Q87 Detect reactivation events (gap > 90 days then an order). Q88 Detect consecutive declining months (2+ negative MoM in a row). Q89 Detect the first month a store crossed Rs1,00,000 revenue. Q90 Detect churn signal: gap to next order is NULL (no next order). Q91 Count distinct sessions per customer per day. Q92 Average session length per device_type. Q93 Detect rapid repeat orders (next order within 1 day). Q94 Detect salary changes per employee across months. Q95 Flag products whose price changed more than 3 times. Q96 Detect a customer's longest active streak (consecutive months with orders). Q97 Flag campaigns whose spend doubled vs previous period. Q98 Detect inventory replenishment (quantity rises vs previous snapshot). Q99 Sessionize calls: new "call burst" when gap > 1 hour per customer. Q100 Build a sessionized web table: session_id, start, end, duration, view_count. Interview grade, edge cases
CONCEPTUAL Q1 Gaps-and-islands: how does (row_number - LAG-based group key) find consecutive runs? Q2 Why MoM growth needs a gap-filled month spine (missing months break LAG). Q3 YoY vs MoM: LAG 12 vs LAG 1 on a monthly grain - pitfalls. Q4 Sessionization: new-session flag -> cumulative sum -> session id; why it works. Q5 Churn signal: LEAD(order_date) IS NULL vs gap-to-today - which and why. Q6 "Previous non-null value": why plain LAG fails on sparse data; the fix. Q7 Detecting streaks of consecutive active months per customer. Q8 Why ORDER BY (date, id) tie-break matters for LAG correctness. Q9 Combining LAG with a moving average (Topic 17) for anomaly detection. Q10 Period-over-period at two grains (store-month and region-month) in one query. Q11 Why growth tables filter the first period (no prior) out or label it. Q12 Reactivation cohorts: define via gap > 90 days then activity. Q13 First-touch to conversion latency via LEAD across event types. Q14 Detect monotonic decline (N consecutive negative deltas). Q15 Why "consecutive days" islands need a date spine, not just order rows. Q16 Compute time-in-state (status durations) using LEAD on a state log. Q17 Run-length encoding of a status series with gaps-and-islands. Q18 Why LAG-based change detection beats comparing to a stored "previous" column. Q19 Compute "days to churn" (last order to a cutoff) with LEAD/CURRENT_DATE. Q20 Multi-offset comparison (vs 1, 3, 12 periods ago) in one query. Q21 Detecting price-change events and the magnitude of each change. Q22 Build a retention curve input (active in month N after signup) with LAG/LEAD. Q23 Why sessionization thresholds belong in a CTE for tunability. Q24 Cumulative streak length that resets on a break. Q25 Combine LAG growth % with NTILE to bucket "fastest-growing" stores. GROWTH TABLES Q26 SCENARIO: CFO wants a MoM revenue growth table per region (revenue, prev, growth %, flag). Q27 YoY monthly revenue growth % per store (LAG 12, gap-filled). Q28 QoQ revenue growth per region with up/down arrows. Q29 MoM AOV growth per store. Q30 MoM units growth % for the top-10 products by revenue. Q31 Compare growth vs 1, 3, and 12 months ago in one row. Q32 MoM new-customer growth per acquisition city. Q33 MoM refund-rate change per category. Q34 WoW active-customer growth per region. Q35 MoM contribution shift: each category's %-of-company change. Q36 MoM gross-margin growth per brand. Q37 Fastest-growing stores: rank by latest MoM growth % (combine with Topic 16 rank). Q38 MoM ad-spend efficiency change per platform. Q39 MoM ticket-volume growth per priority. Q40 Detect the first month each store exceeded its prior peak revenue. Q41 MoM page-view growth per device, gap-filled. Q42 Compounded 3-month growth setup (chain of MoM deltas). Q43 MoM net_salary cost growth per department. Q44 Seasonality check: same-month-last-year compare per region. Q45 MoM growth for new vs returning customer revenue (split then LAG). Q46 Negative-growth alert: stores with 2+ consecutive declining months. Q47 MoM revenue growth with both absolute delta and % delta. Q48 Quarter-over-quarter growth for the top-5 categories. Q49 MoM growth indexed: first month = 100, each month relative. Q50 Full growth pack: per store-month revenue, prev, MoM %, YoY %, flag. GAPS-AND-ISLANDS Q51 SCENARIO: Find each customer's longest streak of consecutive active months. Q52 Consecutive-day order streaks per store. Q53 Identify "islands" of months where a store had revenue (vs gaps). Q54 Longest run of months a product sold continuously. Q55 Consecutive weeks a customer placed at least one order. Q56 Identify gaps (missing months) in each store's revenue timeline. Q57 Run-length of consecutive 5-star reviews per product. Q58 Streak of consecutive on-time deliveries per courier. Q59 Consecutive months an employee's salary stayed unchanged. Q60 Identify continuous in-stock periods per (warehouse, product). Q61 Longest consecutive-day login streak per customer (web_events). Q62 Islands of consecutive profitable months per store. Q63 Consecutive price-stable periods per product (no price change). Q64 Streak of months with positive MoM growth per region. Q65 Group consecutive same-status order runs per customer. Q66 Find the start/end dates of each active island per customer. Q67 Longest gap (out-of-stock island) per product. Q68 Consecutive quarters a brand grew revenue. Q69 Identify reactivation islands (active -> gap -> active) per customer. Q70 Streak of consecutive weeks a campaign ran (spend present). Q71 Run-length encode a customer's tier history. Q72 Consecutive days revenue beat the previous day (winning streak). Q73 Islands of consecutive months with refunds per customer. Q74 Longest consecutive-month payroll run per employee. Q75 Build an islands table: customer, island_start, island_end, length. CHURN, SESSIONS & CHANGE DETECTION Q76 SCENARIO: Flag churn-risk customers: no order in the last 90 days (gap to today). Q77 Reactivation events: order after a > 90-day gap. Q78 Time-to-second-order per customer (first->second latency). Q79 Sessionize web_events: new session when gap > 30 min; output session ids. Q80 Session duration and view count per derived session. Q81 Detect price-change events with old->new and % change per product. Q82 Detect > 50% price jumps (data-entry error candidates). Q83 Detect tier upgrades and downgrades per customer over time. Q84 Detect stock-outs (positive -> 0) and recoveries (0 -> positive). Q85 Detect rating drops (review < previous) per product. Q86 Churn cohort: customers whose last order is in each month. Q87 Detect consecutive declining-revenue months per store (alert). Q88 Average session length per device and per day. Q89 Detect rapid repeat purchases (next order within 24h). Q90 Detect salary changes and their magnitude per employee. Q91 Time-in-status durations from a status log (LEAD on timestamps). Q92 Detect customers slowing down: latest gap > 2x their median gap. Q93 First-vs-last order value change per customer (loyalty value trend). Q94 Detect campaigns whose spend doubled period-over-period. Q95 Web funnel step timing: time between page -> cart -> checkout via LEAD. Q96 Detect the month a customer's spend peaked then declined. Q97 Sessionize calls into bursts (gap > 1h) and count bursts per customer. Q98 Detect inventory replenishment events and their size. Q99 Build a churn dashboard: customer, last_order, days_since, churn_flag, prior_gap. Q100 Full change-log: per product, every price change with date, old, new, %, rank of change. Production scenarios, optimisation
CONCEPTUAL Q1 Architect a growth dashboard comparing vs 1/3/12 periods in one query. Q2 Cohort retention matrix inputs purely via LAG/LEAD + date math. Q3 Gaps-and-islands at scale: the (rn - dense group) trick and its cost. Q4 Sessionization pipeline: threshold -> flag -> cumulative session id -> aggregate. Q5 Anomaly = (value - trailing MA) / trailing stddev; combine Day-17 frame + LAG. Q6 Robust MoM on sparse data: date spine + LAG + COALESCE strategy. Q7 "Previous non-null" via a running max of (value's row when not null) - pattern. Q8 Churn vs reactivation definitions and how LAG/LEAD encode each. Q9 Multi-grain period-over-period (SKU/brand/category) without N queries. Q10 Time-in-state and state-transition matrices from a log via LEAD. Q11 Why compounded growth needs careful chaining (product of (1+gi)). Q12 Funnel timing: median time between steps via LEAD + percentile. Q13 Detect monotonic trends (N consecutive same-sign deltas) generically. Q14 Reproducible cohort timelines across refreshes (anchor on first activity). Q15 Sessionization tuning: choosing the gap threshold from the gap distribution. Q16 Why LAG-based change logs beat trigger-based audit for analytics. Q17 Period-over-period with mixed calendars (fiscal vs ISO week). Q18 Detecting seasonality via YoY LAG and de-seasonalizing. Q19 Combine LAG growth with NTILE to rank fastest/slowest movers. Q20 Building a "days to next purchase" survival-style table. Q21 Streak analytics: longest/current/average streak per entity. Q22 Why sessionization + funnel must share one ordered event stream. Q23 Anomaly suppression: ignore deltas within +/- of a trailing band. Q24 Cohort decay curve from retention deltas. Q25 When to precompute these in an MV (Topic 25) vs on-the-fly. GROWTH & RETENTION SYSTEMS Q26 SCENARIO: Build a per-store growth board: MoM %, QoQ %, YoY %, and a trend flag. Q27 Signup-cohort retention: % of each month's cohort active in months 1-6 (LAG/LEAD + date math). Q28 Multi-offset compare (1/3/12 months ago) per region in one row. Q29 Compounded 6-month growth per store (chain of MoM). Q30 New vs returning revenue MoM growth (split then LAG). Q31 Fastest-growing brands: latest MoM % then NTILE into growth tiers. Q32 Retention curve per acquisition channel (first order channel proxy). Q33 YoY same-month compare per category with seasonality flag. Q34 Cohort revenue indexed to cohort month 0 = 100. Q35 MoM contribution shift: category %-of-company change over time. Q36 Reactivation rate per month (reactivated / churned base). Q37 Customer lifetime value trajectory: cumulative spend with MoM deltas. Q38 Detect decelerating stores: 3 consecutive declining MoM %. Q39 Region revenue YoY with both absolute and % change. Q40 AOV trend per store: MoM AOV growth with up/down streak. Q41 Per-cohort "months to second purchase" distribution. Q42 Growth attribution: which categories drove company MoM change. Q43 Rolling retention: % active in trailing 30/60/90 days per cohort. Q44 MoM churn count and reactivation count side by side. Q45 Top-10 fastest-growing products by YoY units. Q46 Net revenue retention proxy per cohort (this period / prior period spend). Q47 Detect first month a store turned profitable then stayed. Q48 Compounded category growth ranked across the catalog. Q49 Per-customer spend momentum (recent 3-mo vs prior 3-mo). Q50 Full growth+retention pack per region-month (8 metrics). GAPS-AND-ISLANDS & SESSIONS AT SCALE Q51 SCENARIO: Sessionize all web_events (gap > 30 min) and emit session_id, start, end, duration, views. Q52 Longest active-month streak per customer across 50k customers. Q53 Continuous in-stock islands per (warehouse, product) with start/end. Q54 Consecutive-day order streaks per store with streak length. Q55 Run-length encode each customer's tier history into intervals. Q56 Funnel timing: median minutes page->cart->checkout via LEAD per session. Q57 Identify reactivation islands (active->gap->active) and count per customer. Q58 Consecutive profitable months per store with longest run. Q59 Out-of-stock islands and their durations per product. Q60 Group consecutive same-status order runs and their spans. Q61 Login streaks per customer (consecutive days) from web_events. Q62 Price-stability islands per product (no change) with lengths. Q63 Sessionize calls into bursts (gap > 1h) and average burst size. Q64 Continuous-growth islands (consecutive positive MoM) per region. Q65 Time-in-status durations from an order status log (LEAD). Q66 Longest consecutive 5-star review run per product. Q67 Per-session funnel completion flag (reached checkout?). Q68 Streaks of consecutive on-time deliveries per courier. Q69 Identify the dominant session length band per device. Q70 Consecutive payroll months per employee (employment continuity). Q71 Bounce sessions (1 view) vs engaged sessions (>=5 views) per day. Q72 Reactivation latency distribution (gap length before reactivation). Q73 Longest winning streak (revenue beats prior day) per store. Q74 Per-customer cadence islands: stable-frequency vs erratic periods. Q75 Build a sessions fact table from web_events (one row per session). ANOMALY & EXECUTIVE DASHBOARDS Q76 SCENARIO: Daily revenue anomaly board: value, 7-day MA (Topic 17), MoM, z-score, flag. Q77 Detect days where revenue deviates > 2sigma from trailing 30-day mean. Q78 Price-change log: every product price change with old/new/%/rank and date. Q79 Churn dashboard: customer, last_order, days_since, prior_gap, churn_flag. Q80 Retention heatmap inputs: cohort x month-since with retained %. Q81 Sessionized funnel dashboard: sessions, cart rate, checkout rate, median step time. Q82 Store momentum board: MoM %, QoQ %, YoY %, streak, percentile of growth. Q83 Demand-spike detector: product days where units > 3x trailing-7 average. Q84 Reactivation dashboard per month: churned, reactivated, net. Q85 Delivery-degradation alert: courier whose delivery time rose 3 months running. Q86 Inventory volatility board: stock change deltas and stock-out events per product. Q87 Customer health trend: spend momentum + recency + churn risk in one row. Q88 Category growth waterfall MoM (who gained/lost share). Q89 Agent performance trend: resolved/day MoM with streaks. Q90 Anomalous orders: value > customer's trailing-mean by large margin. Q91 Web engagement board: sessions/day, avg duration, MoM growth per device. Q92 Refund-spike detector per category (MoM refund % jump). Q93 Seasonality board: YoY same-month index per region. Q94 Fastest decelerating SKUs (steepest negative YoY units). Q95 Net-new-customer board with MoM and YoY growth. Q96 Executive trend pack per region-month: revenue, MoM, YoY, 3-mo MA, anomaly flag. Q97 First-to-second purchase conversion board per cohort. Q98 Price-war detector: clusters of frequent price changes per brand. Q99 Sessionized conversion funnel with drop-off % per step. Q100 End-to-end exec board: growth + retention + anomaly + churn, per region-month.