Window functions — quiz
10 questions covering this module. OVER, partitioning, ranking, LAG/LEAD and running totals.
The main difference between a window function and GROUP BY:
- Speed
- Window functions retain every row
- Windows only work on numbers
- GROUP BY is deprecated
Answer: Window functions retain every row — That retention is the whole point.
Why must a top-N-per-group query use a subquery?
- Performance
- Window functions cannot be used in WHERE
- PARTITION BY requires it
- To avoid nulls
Answer: Window functions cannot be used in WHERE — Windows evaluate after WHERE, so the filter happens one level up.
SUM(x) OVER (ORDER BY d) returns a running total because:
- ORDER BY sorts output
- ORDER BY changes the default frame to unbounded preceding through current row
- SUM behaves differently in windows
- PARTITION BY is missing
Answer: ORDER BY changes the default frame to unbounded preceding through current row — The default frame changes as soon as ORDER BY appears.
With duplicate dates, RANGE differs from ROWS because:
- RANGE is faster
- RANGE includes all rows sharing the current ORDER BY value
- ROWS ignores nulls
- They are identical
Answer: RANGE includes all rows sharing the current ORDER BY value — That is why moving averages should specify ROWS.
Values 100, 90, 90, 80 with RANK() DESC give:
- 1,2,2,3
- 1,2,2,4
- 1,2,3,4
- 1,1,2,3
Answer: 1,2,2,4 — RANK ties then skips the intervening position.
To keep the latest row per email, use:
- DISTINCT
- ROW_NUMBER partitioned by email, ordered by updated_at DESC, filtered to 1
- GROUP BY email
- RANK filtered to 1
Answer: ROW_NUMBER partitioned by email, ordered by updated_at DESC, filtered to 1 — RANK could return several rows on a tie; ROW_NUMBER returns exactly one.
LAG(revenue) on the first row returns:
- 0
- NULL unless a default is supplied
- The last row
- An error
Answer: NULL unless a default is supplied — The third argument supplies a default.
A month with no data causes LAG to:
- Error
- Compare across the gap silently
- Return zero
- Skip the query
Answer: Compare across the gap silently — Join to a date spine so every period has a row.
Which frame gives a running total?
- ROWS BETWEEN 1 PRECEDING AND CURRENT ROW
- ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
- RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
- No frame at all
Answer: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW — Everything from the start of the partition to the current row.
For a 3-period moving average you should specify ROWS because:
- It is faster
- RANGE would include tied ordering values
- ROWS handles nulls
- RANGE is invalid
Answer: RANGE would include tied ordering values — Ties on the ORDER BY column would widen the window under RANGE.