What window functions do
A window function performs a calculation across a set of rows related to the
current row — a ranking, a running total, the previous row’s value — without
collapsing the result the way GROUP BY does. Every input row stays in the
output. This reference lists the ranking, offset and value functions plus the
OVER() clause they all share, with per-database support.
How it works
The OVER() clause defines the window: how rows are partitioned, ordered, and
framed:
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 rnk,
LAG(salary) OVER (PARTITION BY department ORDER BY salary DESC) AS prev,
SUM(salary) OVER (PARTITION BY department
ORDER BY salary
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running
FROM employees;
PARTITION BY resets the calculation per group, ORDER BY orders rows within
each partition, and the frame clause bounds the rows an aggregate or value
function sees. Ranking and offset functions require ORDER BY. The tool filters
the table as you type and flags dialect support.
Tips and notes
- Window functions run after
WHERE/GROUP BY— you cannot filter on them inWHERE; use a subquery orQUALIFY(where supported). ROWSframes count physical rows;RANGEframes group peer rows with equalORDER BYvalues.- The default frame for an ordered window is
RANGE UNBOUNDED PRECEDING TO CURRENT ROW. LAG/LEADtake optional offset and default arguments:LAG(x, 2, 0).