Interview Q&A · SQL · 14 questions in this topic
Window Functions — SQL Interview Q&A
Analytics without collapsing rows — ranking, running totals, LAG/LEAD and frame semantics. Part of Window Functions · 192 questions in the SQL bank.
What is a window function and how does it differ from GROUP BY?
Answer
Window functions compute over a related row set (the window) while keeping every input row — GROUP BY collapses rows. OVER defines the window (PARTITION BY groups, ORDER BY sequences, frame bounds rows). Row detail plus context in one pass is the superpower.
Rank-without-collapse is the headline use; every row keeps its identity.
Example
SELECT name, department, salary, AVG(salary) OVER (PARTITION BY department) AS dept_avg FROM employees; -- all rows kept, average attached
💡 Keeps-rows-vs-collapses-rows is the GROUP BY contrast.
How do ROW_NUMBER, RANK and DENSE_RANK differ?
Answer
ROW_NUMBER assigns unique 1..N (ties broken arbitrarily). RANK gives ties the same number with gaps after (1,1,3). DENSE_RANK gives ties the same number with no gaps (1,1,2). Nth-highest-salary wants DENSE_RANK; pagination wants ROW_NUMBER; leaderboard gaps want RANK.
Tie semantics decide — state the tie behavior, not just the names.
Key points
- 1ROW_NUMBER — unique, arbitrary tie-break.
- 2RANK — ties share, gaps follow.
- 3DENSE_RANK — ties share, no gaps.
Example
SELECT name, salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS r FROM employees;
💡 Tie behavior is the differentiator to recite.
How do PARTITION BY and ORDER BY inside OVER work?
Answer
PARTITION BY splits rows into independent windows (per department) — computations restart per partition. ORDER BY sequences rows within each window — required for running totals, rankings and LAG/LEAD meaning. Omit PARTITION for whole-result windows; omit ORDER where order is irrelevant (plain per-group averages).
Partition scopes, order sequences — the two knobs.
Example
SELECT name, SUM(salary) OVER (PARTITION BY department) AS dept_total, SUM(salary) OVER () AS grand_total FROM employees;
How do you compute running totals (cumulative SUM)?
Answer
SUM(x) OVER (ORDER BY seq) accumulates in sequence order — the default frame (RANGE from start to current peer) usually suffices with unique ordering. For explicit control use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
Duplicate ORDER BY values make default RANGE frames jump — unique sequencing (id, timestamp) keeps totals stepwise.
Example
SELECT id, salary, SUM(salary) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running FROM employees;
How do LAG and LEAD access neighboring rows?
Answer
LAG(col, n, default) reads n rows before the current row in window order; LEAD reads after. Defaults fill edges (first row has no LAG). Partitioned by entity with time ordering, they compute deltas, prior values, and session boundaries — month-over-month, previous-status patterns.
Self-join alternatives need range conditions; LAG/LEAD need only ordering.
Example
SELECT month, revenue, revenue - LAG(revenue, 1, 0) OVER (ORDER BY month) AS growth FROM monthly_sales;
💡 Prior/next-row access without self-joins is the pitch.
What are window frames (ROWS, RANGE, GROUPS)?
Answer
Frames bound which peer rows participate: ROWS counts physical rows (precise, stepwise), RANGE groups by ORDER BY value peers (ties move together), GROUPS groups peer sets. BETWEEN ... AND ... sets start/end (UNBOUNDED PRECEDING, CURRENT ROW, n PRECEDING/FOLLOWING).
Default (RANGE to current peer) surprises with duplicate keys — explicit ROWS is the predictable choice.
Key points
- 1ROWS — physical offsets, stepwise.
- 2RANGE — value peers move together.
- 3GROUPS — peer-group granularity.
Example
-- moving 3-row average (explicit frame): SELECT AVG(salary) OVER (ORDER BY id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) FROM employees;
💡 Explicit frames beat defaults is the senior habit.
Why can window functions not appear in WHERE (and what is the workaround)?
Answer
Windows evaluate in SELECT — after WHERE (execution order). Filtering on them needs an outer query or QUALIFY (Snowflake/BigQuery/Snowflake-style engines) which filters post-window inline.
Compute-in-subquery/CTE, filter-outside is the portable pattern.
Example
SELECT * FROM ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY department ORDER BY salary DESC) AS rn FROM employees) t WHERE rn <= 3;
How do FIRST_VALUE, LAST_VALUE and NTH_VALUE work?
Answer
They pick positional values within the window frame: FIRST_VALUE (window start), LAST_VALUE (frame end — needs explicit ROWS ... FOLLOWING frame or it returns the current row!), NTH_VALUE(nth). LAST_VALUE's default-frame trap (current row, not partition end) is the famous gotcha.
Explicit full-partition frames make LAST_VALUE behave as named.
Example
-- last salary in department (explicit frame required!): SELECT LAST_VALUE(salary) OVER ( PARTITION BY department ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) FROM employees;
How do you compute percent-of-total per row?
Answer
Divide the row value by the Grand total window (SUM() OVER ()) — decimal-cast first. Partitioned variants give group shares. This keeps row detail impossible under GROUP BY.
The empty OVER () (whole result as one window) is the idiom to memorize.
Example
SELECT name, salary, salary * 100.0 / SUM(salary) OVER () AS pct_of_total FROM employees;
How do you detect gaps and islands (sessionization)?
Answer
Islands: subtract a row-number sequence from the ordered key — constant differences mark contiguous blocks, GROUP BY the difference. Sessions: LAG timestamps, flag gaps over threshold, cumulative SUM of flags as session ids.
Difference-of-sequences is the gaps-and-islands insight; flag-plus-cumulative-sum is sessionization.
Example
-- island key: constant (id - row_number) per contiguous block SELECT MIN(id) AS start_id, MAX(id) AS end_id FROM (SELECT id, id - ROW_NUMBER() OVER (ORDER BY id) AS grp FROM tickets) t GROUP BY grp;
💡 Constant-difference-per-block is the pattern to whiteboard.
How do NTILE and PERCENT_RANK bucket rows?
Answer
NTILE(n) splits ordered rows into n near-equal buckets (quartiles, deciles) — uneven remainders go to early buckets. PERCENT_RANK gives relative rank 0..1 ((rank-1)/(rows-1)); CUME_DIST gives cumulative share. Bucketing serves A/B deciles, salary bands, and stratified sampling.
NTILE buckets count; PERCENT_RANK positions relatively.
Example
SELECT name, salary, NTILE(4) OVER (ORDER BY salary) AS quartile FROM employees;
Can you use DISTINCT or GROUP BY with window functions?
Answer
Yes — windows evaluate after GROUP BY/DISTINCT over their output rows. GROUP then window (rank departments by total), or window then outer GROUP (aggregate windowed flags). DISTINCT with windows dedups post-computation rows.
Order of operations (GROUP → window → DISTINCT → ORDER) composes legally.
Example
SELECT department, SUM(salary) AS total, RANK() OVER (ORDER BY SUM(salary) DESC) AS r FROM employees GROUP BY department;
💡 Aggregates feed windows directly is the composition to demonstrate.
How do you find the latest row per group with windows (and alternatives)?
Answer
ROW_NUMBER() partitioned by group ordered by time DESC, outer filter rn = 1 — portable, flexible (ties broken deterministically with id). Alternatives: PostgreSQL DISTINCT ON (concise, non-portable), LATERAL LIMIT join (index-friendly), correlated MAX subquery.
ROW_NUMBER is the default answer; DISTINCT ON the PostgreSQL shortcut.
Example
SELECT * FROM (SELECT *, ROW_NUMBER() OVER ( PARTITION BY customer_id ORDER BY created_at DESC, id DESC) AS rn FROM orders) t WHERE rn = 1;
Which databases support window functions?
Answer
PostgreSQL, SQL Server, Oracle, MySQL 8+, SQLite, Snowflake/BigQuery — all modern engines. MySQL before 8.0 and old SQLite lack them (rewrite with correlated subqueries or self-joins). ROW_NUMBER/RANK/LEAD/LAG/SUM-OVER are the portable core; advanced frames and QUALIFY vary.
Version-check before relying on windows in shared codebases.
Example
-- SELECT VERSION(); -- confirm MySQL 8+ / modern SQLite first
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission