Window functions are the most-asked topic in 2026 SQL interviews — and the single biggest unlock for analytics work. They let you compute aggregates and rankings without collapsing rows the way GROUP BY does.
What is a window function?
A window function performs a calculation across a set of rows ("the window") that are related to the current row. The output is still one row per input row — that's what makes it different from GROUP BY.
OVER and PARTITION BY
-- Show each employee's salary alongside their department's averageSELECTname,department,salary,AVG(salary) OVER (PARTITION BY department) AS dept_avg,salary - AVG(salary) OVER (PARTITION BY department) AS diff_from_avgFROM employees;
The OVER (PARTITION BY ...) clause defines the window. Without PARTITION BY, the window is the entire result set:
SELECT name, salary,salary / SUM(salary) OVER () AS share_of_payrollFROM employees;
ROW_NUMBER, RANK, DENSE_RANK
| Function | Behaviour on ties |
|---|---|
| ROW_NUMBER() | always sequential — 1, 2, 3, 4 |
| RANK() | gaps after ties — 1, 2, 2, 4 |
| DENSE_RANK() | no gaps — 1, 2, 2, 3 |
SELECT name, department, salary,ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn,RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rk,DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS drFROM employees;
LAG and LEAD
Useful for time-series questions: "what was the previous value?" / "what's the next?"
-- Days between a user's loginsSELECT user_id, login_at,LAG(login_at) OVER (PARTITION BY user_id ORDER BY login_at) AS prev_login,login_at - LAG(login_at) OVER (PARTITION BY user_id ORDER BY login_at) AS gapFROM logins;-- Compare today's revenue to yesterday'sSELECT day, revenue,LAG(revenue) OVER (ORDER BY day) AS yesterday,revenue - LAG(revenue) OVER (ORDER BY day) AS day_over_dayFROM daily_metrics;
Running totals
SELECT order_date,amount,SUM(amount) OVER (ORDER BY order_dateROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_totalFROM orders;
Top-N per group
The single most-asked SQL interview pattern: "find the 3 highest-paid employees per department."
WITH ranked AS (SELECT name, department, salary,DENSE_RANK() OVER (PARTITION BY departmentORDER BY salary DESC) AS rkFROM employees)SELECT name, department, salaryFROM rankedWHERE rk <= 3ORDER BY department, salary DESC;
Key takeaways
- 01Window functions compute aggregates without collapsing rows.
- 02OVER (PARTITION BY ...) defines the window; ORDER BY orders rows within it.
- 03Use ROW_NUMBER for unique rankings, RANK / DENSE_RANK to handle ties.
- 04LAG/LEAD look at previous/next rows — perfect for time-series gaps.
- 05The Top-N-per-group pattern is the most-asked window question — memorise it.
