Black Friday30% off ProOffer ends 2 December at 23:59 UK time.
QueryCasequerycase.com
Bureau reference guide

SQL Window Functions Cheat Sheet

OVER, frames, ranking, LAG and LEAD, and the patterns interviews ask for, each with an example you can copy.

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-- notecomments
01

The OVER Clause

Deep dive: SQL window functions explained
OVER ()

Runs the function across every row and writes the answer beside each one. Unlike GROUP BY, no rows are lost.

Example
SELECT name, salary,
  AVG(salary) OVER () AS company_avg
FROM employees;
PARTITION BY

Splits the rows into groups and runs the function inside each group on its own.

Example
SELECT name, department, salary,
  AVG(salary) OVER (PARTITION BY department) AS dept_avg
FROM employees;
ORDER BY inside OVER

Sets the order the function reads the rows in. With SUM or COUNT it turns a total into a running total.

Example
SELECT region, month, revenue,
  SUM(revenue) OVER (
    PARTITION BY region ORDER BY month
  ) AS running_total
FROM sales;
TipThe ORDER BY inside OVER steers the calculation. The ORDER BY at the end of a query only sorts the output.
02

Ranking

ROW_NUMBER()

Numbers the rows 1, 2, 3 in the window's order. Two equal values still get different numbers.

Example
SELECT name, department, salary,
  ROW_NUMBER() OVER (
    PARTITION BY department ORDER BY salary DESC
  ) AS rn
FROM employees;
TipAdd a tiebreaker (ORDER BY salary DESC, name) so the numbering comes out the same every run.
RANK / DENSE_RANK

Equal values share a rank. RANK then skips (1, 2, 2, 4); DENSE_RANK does not (1, 2, 2, 3).

Example
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 group

Number each group's rows in a CTE, then keep the first few in the next query.

Example
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;
TipWHERE runs before window functions, so it cannot filter on one in the same query. That is what the CTE is for.
03

Previous and Next Rows

LAG / LEAD

A value from an earlier row (LAG) or a later one (LEAD), in the window's order.

Example
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;
TipEach region's first row has no row before it, so LAG gives NULL there. LAG(revenue, 1, 0) gives 0 instead.
Growth on last month

This month minus last month, as a percentage of last month.

Example
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;
TipOn monthly rows with no months missing, LAG(revenue, 12) is the same month last year.
FIRST_VALUE / LAST_VALUE

The first or last value in the frame. LAST_VALUE needs a frame that reaches the end of the partition.

Example
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;
TipWith ORDER BY and no frame, the frame stops at the current row, so LAST_VALUE returns the current row's own value.
IGNORE NULLS

Makes LAST_VALUE skip NULLs, so a gap shows the last value that was not NULL.

Example
SELECT sensor, read_at, value,
  LAST_VALUE(value IGNORE NULLS) OVER (
    PARTITION BY sensor ORDER BY read_at
  ) AS last_known
FROM readings;
TipNot every database supports IGNORE NULLS. COALESCE(value, LAG(value) OVER (...)) is no substitute: it only fills a gap one row long.
04

Running Totals and Shares

Running maximum

The highest value so far: MAX with an ORDER BY.

Example
SELECT region, month, revenue,
  MAX(revenue) OVER (PARTITION BY region ORDER BY month) AS best_so_far
FROM sales;
Share of the total

Each row as a percentage of everything. OVER () with nothing inside is the whole table.

Example
SELECT name, salary,
  ROUND(100.0 * salary / SUM(salary) OVER (), 1) AS pct_of_payroll
FROM employees;
TipWrite 100.0, not 100: some databases divide two whole numbers into a whole number.
Windows after GROUP BY

Windows run after GROUP BY, so they see one row per group. Wrap the aggregate to total the groups.

Example
SELECT department,
  SUM(salary) AS dept_total,
  SUM(SUM(salary)) OVER () AS company_total
FROM employees
GROUP BY department;
05

Frames

ROWS BETWEEN n PRECEDING AND CURRENT ROW

A moving window: this row and the n before it. The shape behind every rolling average.

Example
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;
TipThe current row counts: 2 PRECEDING AND CURRENT ROW is three rows. The first rows of each partition average fewer.
Other ROWS frames

Each end can be UNBOUNDED PRECEDING, n PRECEDING, CURRENT ROW, n FOLLOWING or UNBOUNDED FOLLOWING.

Example
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 INTERVAL

A frame measured in time, not rows. RANGE uses the ORDER BY value, so an hour back is an hour back.

Example
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;
TipROWS counts rows and cannot take an INTERVAL.
The default frame

With 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.

Pattern
SUM(x) OVER (ORDER BY d)
-- is the same as
SUM(x) OVER (
  ORDER BY d
  RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)
TipWant one row at a time, even on ties? Write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
06

Buckets and Percentiles

NTILE(n)

Deals the rows, in order, into n buckets as evenly as it can.

Example
SELECT name, salary,
  NTILE(4) OVER (ORDER BY salary DESC) AS quartile
FROM employees;
TipSpare rows go to the first buckets: 10 rows in 4 buckets come out 3, 3, 2 and 2.
PERCENT_RANK / CUME_DIST

Where 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.

Example
SELECT name, salary,
  PERCENT_RANK() OVER (ORDER BY salary) AS pct_rank,
  CUME_DIST() OVER (ORDER BY salary) AS cume_dist
FROM employees;
07

Filtering and Naming Windows

Deep dive: why WHERE cannot see a window
QUALIFY

Filters on a window function's result in the same query, the way HAVING filters groups.

Example
SELECT name, department, salary
FROM employees
QUALIFY ROW_NUMBER() OVER (
  PARTITION BY department ORDER BY salary DESC
) = 1;
TipSnowflake, BigQuery and DuckDB have QUALIFY. PostgreSQL, MySQL and SQL Server do not: use a CTE and WHERE, as in Top N per group.
WINDOW

Names a window once so several functions can share it. It goes after FROM, WHERE, GROUP BY and HAVING.

Example
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);
08

Patterns

Gaps and islands

Days in an unbroken run share the same date minus row number, so group by it to measure each run.

Example
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;
TipIt needs one row per user per day. On a whole-number column, drop the CAST: night - ROW_NUMBER() OVER (...).
Sessions

Split events into sessions after a gap: the gap from LAG, a flag where a session starts, then a running SUM of the flags.

Example
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;
TipWindow functions cannot nest, so each step gets its own CTE. DATEDIFF is spelled differently in each database.
Cohorts

Each customer's first month beside every order, ready to count who came back in later months.

Example
SELECT customer_id, order_date,
  MIN(DATE_TRUNC('month', order_date)) OVER (
    PARTITION BY customer_id
  ) AS cohort_month
FROM orders;
SQL Window Functions Cheat Sheet · QueryCaseThe full course is at querycase.com