A window function works out a value from a group of rows and writes it beside each row, without collapsing them the way GROUP BY does. Everything that shapes the window goes inside the brackets after OVER, in this order.
SELECT name, department, salary, SUM(salary) OVER ( -- the function, then OVER PARTITION BY department -- one window per department ORDER BY salary DESC -- the order inside each window ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW -- the frame ) AS running_total FROM employees;
Every part inside the brackets is optional: OVER () on its own is the whole table.
SELECTkeywordsCOUNTfunctions'text'text values123numbers-- notecommentsThe OVER Clause
OVER ()Runs the function across every row and writes the answer beside each one. Unlike GROUP BY, no rows are lost.
SELECT name, salary, AVG(salary) OVER () AS company_avg FROM employees;
PARTITION BYSplits the rows into groups and runs the function inside each group on its own.
SELECT name, department, salary, AVG(salary) OVER (PARTITION BY department) AS dept_avg FROM employees;
ORDER BY inside OVERSets the order the function reads the rows in. With SUM or COUNT it turns a total into a running total.
SELECT region, month, revenue, SUM(revenue) OVER ( PARTITION BY region ORDER BY month ) AS running_total FROM sales;
Ranking
ROW_NUMBER()Numbers the rows 1, 2, 3 in the window's order. Two equal values still get different numbers.
SELECT name, department, salary, ROW_NUMBER() OVER ( PARTITION BY department ORDER BY salary DESC ) AS rn FROM employees;
RANK / DENSE_RANKEqual values share a rank. RANK then skips (1, 2, 2, 4); DENSE_RANK does not (1, 2, 2, 3).
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) AS rnk, DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk FROM employees;
Top N per groupNumber each group's rows in a CTE, then keep the first few in the next query.
WITH ranked AS ( SELECT name, department, salary, ROW_NUMBER() OVER ( PARTITION BY department ORDER BY salary DESC ) AS rn FROM employees ) SELECT name, department, salary FROM ranked WHERE rn <= 2;
Previous and Next Rows
LAG / LEADA value from an earlier row (LAG) or a later one (LEAD), in the window's order.
SELECT region, month, revenue, LAG(revenue) OVER (PARTITION BY region ORDER BY month) AS last_month, LEAD(revenue) OVER (PARTITION BY region ORDER BY month) AS next_month FROM sales;
Growth on last monthThis month minus last month, as a percentage of last month.
SELECT region, month, revenue, ROUND(100.0 * (revenue - LAG(revenue) OVER (PARTITION BY region ORDER BY month)) / LAG(revenue) OVER (PARTITION BY region ORDER BY month), 1) AS growth_pct FROM sales;
FIRST_VALUE / LAST_VALUEThe first or last value in the frame. LAST_VALUE needs a frame that reaches the end of the partition.
SELECT region, month, revenue, FIRST_VALUE(revenue) OVER (PARTITION BY region ORDER BY month) AS first_month, LAST_VALUE(revenue) OVER ( PARTITION BY region ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) AS latest_month FROM sales;
IGNORE NULLSMakes LAST_VALUE skip NULLs, so a gap shows the last value that was not NULL.
SELECT sensor, read_at, value, LAST_VALUE(value IGNORE NULLS) OVER ( PARTITION BY sensor ORDER BY read_at ) AS last_known FROM readings;
Frames
ROWS BETWEEN n PRECEDING AND CURRENT ROWA moving window: this row and the n before it. The shape behind every rolling average.
SELECT region, month, revenue, AVG(revenue) OVER ( PARTITION BY region ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW ) AS rolling_3 FROM sales;
Other ROWS framesEach end can be UNBOUNDED PRECEDING, n PRECEDING, CURRENT ROW, n FOLLOWING or UNBOUNDED FOLLOWING.
SELECT region, month, revenue, AVG(revenue) OVER (PARTITION BY region ORDER BY month ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS centred_avg, MAX(revenue) OVER (PARTITION BY region ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS best_before FROM sales;
RANGE BETWEEN INTERVALA frame measured in time, not rows. RANGE uses the ORDER BY value, so an hour back is an hour back.
SELECT user_id, event_at, COUNT(*) OVER ( PARTITION BY user_id ORDER BY event_at RANGE BETWEEN INTERVAL '1 hour' PRECEDING AND CURRENT ROW ) AS events_last_hour FROM events;
The default frameWith ORDER BY and no frame written, the frame runs from the partition's first row to the current one, and rows that tie on the ORDER BY value share one result.
SUM(x) OVER (ORDER BY d) -- is the same as SUM(x) OVER ( ORDER BY d RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW )
Buckets and Percentiles
NTILE(n)Deals the rows, in order, into n buckets as evenly as it can.
SELECT name, salary, NTILE(4) OVER (ORDER BY salary DESC) AS quartile FROM employees;
PERCENT_RANK / CUME_DISTWhere a row sits, from 0 to 1. PERCENT_RANK is (rank - 1) / (rows - 1). CUME_DIST is the share of rows at or before this one, ties included.
SELECT name, salary, PERCENT_RANK() OVER (ORDER BY salary) AS pct_rank, CUME_DIST() OVER (ORDER BY salary) AS cume_dist FROM employees;
Filtering and Naming Windows
QUALIFYFilters on a window function's result in the same query, the way HAVING filters groups.
SELECT name, department, salary FROM employees QUALIFY ROW_NUMBER() OVER ( PARTITION BY department ORDER BY salary DESC ) = 1;
WINDOWNames a window once so several functions can share it. It goes after FROM, WHERE, GROUP BY and HAVING.
SELECT region, month, revenue, LAG(revenue) OVER w AS last_month, SUM(revenue) OVER w AS running_total FROM sales WINDOW w AS (PARTITION BY region ORDER BY month);
Patterns
Gaps and islandsDays in an unbroken run share the same date minus row number, so group by it to measure each run.
WITH marked AS ( SELECT user_id, login_date, login_date - CAST(ROW_NUMBER() OVER ( PARTITION BY user_id ORDER BY login_date ) AS INTEGER) AS island FROM logins ) SELECT user_id, MIN(login_date) AS first_day, MAX(login_date) AS last_day, COUNT(*) AS days FROM marked GROUP BY user_id, island;
SessionsSplit events into sessions after a gap: the gap from LAG, a flag where a session starts, then a running SUM of the flags.
WITH gaps AS ( SELECT user_id, event_at, DATEDIFF('minute', LAG(event_at) OVER (PARTITION BY user_id ORDER BY event_at), event_at) AS gap_min FROM events ), flagged AS ( SELECT user_id, event_at, CASE WHEN gap_min IS NULL OR gap_min > 30 THEN 1 ELSE 0 END AS new_session FROM gaps ) SELECT user_id, event_at, SUM(new_session) OVER ( PARTITION BY user_id ORDER BY event_at ) AS session_id FROM flagged;
CohortsEach customer's first month beside every order, ready to count who came back in later months.
SELECT customer_id, order_date, MIN(DATE_TRUNC('month', order_date)) OVER ( PARTITION BY customer_id ) AS cohort_month FROM orders;


