Interview Q&A · SQL · 14 questions in this topic

Window Functions — SQL Interview Q&A

All SQL topics

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

Example.sqlsql
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

  1. 1ROW_NUMBER — unique, arbitrary tie-break.
  2. 2RANK — ties share, gaps follow.
  3. 3DENSE_RANK — ties share, no gaps.

Example

Example.sqlsql
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

Example.sqlsql
SELECT name,
  SUM(salary) OVER (PARTITION BY department) AS dept_total,
  SUM(salary) OVER () AS grand_total
FROM employees;

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits