What are window functions? Solve "top N per group" and running totals.
A window function computes a value for each row using a set of related rows (the window), without collapsing rows the way GROUP BY does.
Syntax
function() OVER (PARTITION BY ... ORDER BY ... ROWS/RANGE frame)
PARTITION BYsplits rows into groups (like GROUP BY, but rows are kept).ORDER BYorders rows inside each partition.- The frame (
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) limits which rows feed the calculation.
Common functions
- Ranking:
ROW_NUMBER()(always unique),RANK()(gaps after ties: 1,1,3),DENSE_RANK()(no gaps: 1,1,2),NTILE(n). - Offsets:
LAG(col),LEAD(col)for previous and next row: month-over-month change, session gaps. - Aggregates as windows:
SUM(...) OVER (...)for running totals,AVGfor moving averages. FIRST_VALUE,LAST_VALUE(watch the default frame).
Supported by PostgreSQL, MySQL 8+, Oracle, SQL Server and Cloud SQL.
Example
sql
-- Top 3 highest-paid employees per department (ties included with DENSE_RANK)
WITH ranked AS (
SELECT e.*,
DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
FROM employees e
)
SELECT department_id, name, salary
FROM ranked
WHERE rnk <= 3;
-- Running total and month-over-month change of revenue
SELECT month,
revenue,
SUM(revenue) OVER (ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total,
revenue - LAG(revenue) OVER (ORDER BY month) AS change_vs_prev
FROM monthly_revenue
ORDER BY month;
-- Second highest salary overall (a classic)
SELECT DISTINCT salary
FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS r FROM employees) t
WHERE r = 2;Follow-up questions interviewers ask
Try answering each one before you open it.
Why does LAST_VALUE often return the current row?
With ORDER BY in the window, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, so the "last" row of the frame is the current one. Specify ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, or use FIRST_VALUE with the opposite ordering.