SQL Window Functions Cheatsheet
Every SQL window function with a worked example: ranking, offset and aggregate windows, frame clauses, QUALIFY, and the recipes they exist to solve.
The example table
orders
+----------+-------------+------------+---------+--------+
| order_id | customer_id | order_date | channel | amount |
+----------+-------------+------------+---------+--------+
| 1001 | 7 | 2026-01-04 | app | 1200 |
| 1002 | 7 | 2026-01-19 | web | 450 |
| 1003 | 7 | 2026-02-02 | app | 980 |
| 1004 | 9 | 2026-01-08 | web | 2300 |
| 1005 | 9 | 2026-02-11 | app | 310 |
| 1006 | 9 | 2026-02-11 | web | 310 |
+----------+-------------+------------+---------+--------+<function>(<args>) OVER (
PARTITION BY customer_id -- independent groups (optional)
ORDER BY order_date, order_id -- sequence within a group (optional)
ROWS BETWEEN 2 PRECEDING -- the frame (optional)
AND CURRENT ROW
)
-- Name it once and reuse it:
SELECT
order_id,
SUM(amount) OVER w AS running_total,
ROW_NUMBER() OVER w AS n
FROM orders
WINDOW w AS (PARTITION BY customer_id ORDER BY order_date, order_id);Always make the ORDER BY inside a window deterministic. ORDER BY order_date alone leaves orders 1005 and 1006 tied, so ROW_NUMBER() may assign them differently on every run — including differently between your test and production clusters. Add a unique tiebreaker such as order_id.
Ranking functions
These need an ORDER BY inside the window to mean anything — several engines reject the window without one — and they ignore the frame clause entirely.
| Function | Returns | Ties |
|---|---|---|
| ROW_NUMBER() | A unique sequential integer, 1..n, per partition. | Broken arbitrarily — tied rows get different numbers. |
| RANK() | Position with gaps. | Ties share a rank; the next rank skips ahead (1, 2, 2, 4). |
| DENSE_RANK() | Position without gaps. | Ties share a rank; the next rank continues (1, 2, 2, 3). |
| PERCENT_RANK() | (rank − 1) / (total rows − 1), so it runs from 0 to 1. | Ties share a value. A single-row partition returns 0. |
| CUME_DIST() | Fraction of rows at or before the current row, from just above 0 to 1. | Ties all take the value at the end of the tie group. |
| NTILE(n) | Bucket number 1..n, splitting the partition as evenly as it can. | Earlier buckets absorb the remainder when rows do not divide evenly. |
SELECT
customer_id, order_id, amount,
ROW_NUMBER() OVER w AS rn,
RANK() OVER w AS rnk,
DENSE_RANK() OVER w AS dense,
ROUND(PERCENT_RANK() OVER w, 2) AS pct_rank,
ROUND(CUME_DIST() OVER w, 2) AS cume,
NTILE(2) OVER w AS half
FROM orders
WINDOW w AS (PARTITION BY customer_id ORDER BY amount DESC, order_id);
-- customer 9: 2300 -> rn 1, rnk 1, dense 1
-- 310 -> rn 2, rnk 2, dense 2 (order 1005)
-- 310 -> rn 3, rnk 2, dense 2 (order 1006, tied on amount)-- Two biggest orders per customer.
SELECT customer_id, order_id, amount
FROM (
SELECT o.*,
ROW_NUMBER() OVER (PARTITION BY customer_id
ORDER BY amount DESC, order_id) AS rn
FROM orders o
) t
WHERE rn <= 2;
-- Use RANK() instead if you want to keep every row tied at the cut-off,
-- which for "top 2" means you may get three rows back.Offset and value functions
These read a specific row relative to the current one. LAG and LEAD ignore the frame; FIRST_VALUE, LAST_VALUE and NTH_VALUE respect it — which is exactly where people get caught.
| Function | Returns |
|---|---|
| LAG(expr, offset, default) | The value offset rows earlier in the partition (default offset 1). Returns default, or NULL, when there is no such row. |
| LEAD(expr, offset, default) | The value offset rows later. Same NULL behaviour at the end of the partition. |
| FIRST_VALUE(expr) | The first value in the frame — with the default frame, the first row of the partition. |
| LAST_VALUE(expr) | The last value in the frame. With the default frame that is the current row, which is almost never what you meant. |
| NTH_VALUE(expr, n) | The nth value in the frame, counting from the frame start. |
| IGNORE NULLS | Modifier supported by several engines (LAG(x) IGNORE NULLS OVER (...)) that skips NULL values when picking the row. Not available in PostgreSQL or MySQL — emulate it with a conditional running MAX. |
SELECT
customer_id, order_date, amount,
LAG(order_date) OVER w AS prev_order_date,
order_date - LAG(order_date) OVER w AS days_since_prev,
amount - LAG(amount, 1, 0) OVER w AS delta_vs_prev,
LEAD(order_date) OVER w AS next_order_date
FROM orders
WINDOW w AS (PARTITION BY customer_id ORDER BY order_date, order_id);
-- Date subtraction syntax varies: DATEDIFF(day, a, b) on Redshift and
-- SQL Server, DATEDIFF(b, a) on Spark SQL and MySQL, plain "b - a" on
-- PostgreSQL DATE columns.SELECT
order_id,
-- WRONG: the default frame ends at the current row, so this just
-- returns the current row's channel.
LAST_VALUE(channel) OVER (PARTITION BY customer_id
ORDER BY order_date, order_id) AS wrong,
-- RIGHT: extend the frame to the end of the partition.
LAST_VALUE(channel) OVER (PARTITION BY customer_id
ORDER BY order_date, order_id
ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING) AS latest_channel,
-- Or flip the sort and use FIRST_VALUE, which needs no frame at all.
FIRST_VALUE(channel) OVER (PARTITION BY customer_id
ORDER BY order_date DESC, order_id DESC) AS also_latest
FROM orders;Aggregates as window functions
Any aggregate — SUM, AVG, COUNT, MIN, MAX, STDDEV, ARRAY_AGG, STRING_AGG — becomes a window function when you add OVER. Whether it accumulates or covers the whole partition depends entirely on the frame.
SELECT
customer_id, order_date, amount,
-- ORDER BY present -> default frame accumulates: a running total.
SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date, order_id)
AS running_total,
-- No ORDER BY -> the frame is the whole partition: a group total
-- reported on every detail row.
SUM(amount) OVER (PARTITION BY customer_id) AS customer_total,
-- Empty OVER () -> the whole result set.
ROUND(100.0 * amount / SUM(amount) OVER (), 1) AS pct_of_all_orders,
COUNT(*) OVER (PARTITION BY customer_id) AS orders_by_customer,
AVG(amount) OVER (PARTITION BY customer_id) AS avg_basket
FROM orders;-- Last three orders, including the current one.
AVG(amount) OVER (PARTITION BY customer_id
ORDER BY order_date, order_id
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
-- Trailing 7 calendar days, regardless of how many orders fall inside.
-- RANGE compares VALUES of the ORDER BY column, so missing days are
-- handled correctly and duplicate days are all included.
AVG(amount) OVER (PARTITION BY customer_id
ORDER BY order_date
RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW)
-- Centred 3-row window: one back, one forward.
AVG(amount) OVER (ORDER BY order_date
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)Interval-based RANGE frames need a date, timestamp or numeric ORDER BY column and are supported by PostgreSQL 11+, Spark SQL, Snowflake, BigQuery and DuckDB among others. The interval literal syntax differs slightly per engine — Spark writes INTERVAL 6 DAYS, PostgreSQL writes INTERVAL '6 days'.
Frames — ROWS, RANGE and GROUPS
| Clause | Meaning |
|---|---|
| ROWS | Counts physical rows. 2 PRECEDING means exactly two rows back, ties or not. Predictable — the default choice. |
| RANGE | Compares the *value* of the ORDER BY expression. All rows sharing the current row’s value are peers and are included together. |
| GROUPS | Counts distinct peer groups rather than rows: 1 PRECEDING means the previous group of tied values. Supported by PostgreSQL 11+ and DuckDB; not universal. |
| UNBOUNDED PRECEDING | Start of the partition. |
| UNBOUNDED FOLLOWING | End of the partition. |
| CURRENT ROW | Under ROWS, this row. Under RANGE, this row and every row tied with it on the ORDER BY value. |
| n PRECEDING / n FOLLOWING | Offset in rows (ROWS), in values (RANGE), or in peer groups (GROUPS). |
| EXCLUDE CURRENT ROW | GROUP | TIES | NO OTHERS | Removes rows from an otherwise-computed frame — for example a moving average of the neighbours that ignores the current point. PostgreSQL 11+ and DuckDB; not universal. |
-- ORDER BY present, no explicit frame:
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
-> accumulates from the start of the partition,
and includes ALL rows tied with the current row.
-- No ORDER BY at all:
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
-> the entire partition.
-- Why the tie behaviour matters: customer 9 has two orders on 2026-02-11.
SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date)
-- both 2026-02-11 rows report 2920 = 2300 + 310 + 310
SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date, order_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
-- 2610 then 2920 — a true per-row running total.Filtering on a window result
FROM / JOIN
-> WHERE -- cannot see window functions
-> GROUP BY
-> HAVING -- cannot see window functions
-> WINDOW FUNCTIONS -- evaluated here, over the post-HAVING rows
-> SELECT / DISTINCT
-> QUALIFY -- where supported: filters on window results
-> ORDER BY
-> LIMIT / OFFSET-- Portable: CTE + filter. Works everywhere.
WITH ranked AS (
SELECT o.*,
ROW_NUMBER() OVER (PARTITION BY order_id
ORDER BY ingested_at DESC) AS rn
FROM raw_orders o
)
SELECT * FROM ranked WHERE rn = 1;
-- Same thing with QUALIFY (Snowflake, BigQuery, Databricks SQL, DuckDB,
-- Teradata). No subquery, and the intent reads in one line.
SELECT *
FROM raw_orders
QUALIFY ROW_NUMBER() OVER (PARTITION BY order_id
ORDER BY ingested_at DESC) = 1;A window function cannot be nested inside another window function or inside an aggregate. To rank a sum, compute the sum in one CTE and rank it in the next — the engine will not fold that for you.
Recipes
WITH monthly AS (
SELECT DATE_TRUNC('month', order_date) AS month,
SUM(amount) AS revenue
FROM orders
GROUP BY 1
)
SELECT
month, revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_revenue,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
/ NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 1) AS mom_pct
FROM monthly
ORDER BY month;WITH marked AS (
SELECT user_id, event_ts,
CASE WHEN event_ts - LAG(event_ts) OVER (PARTITION BY user_id
ORDER BY event_ts)
> INTERVAL '30 minutes'
OR LAG(event_ts) OVER (PARTITION BY user_id
ORDER BY event_ts) IS NULL
THEN 1 ELSE 0 END AS is_new_session
FROM events
)
SELECT user_id, event_ts,
SUM(is_new_session) OVER (PARTITION BY user_id
ORDER BY event_ts
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW) AS session_no
FROM marked;-- The trick: for consecutive dates, (date - row_number) is constant,
-- so it becomes a group key for each unbroken run. Date-minus-integer is
-- PostgreSQL syntax; use DATE_SUB or DATEADD on other engines.
WITH d AS (
SELECT DISTINCT customer_id, order_date FROM orders
),
grouped AS (
SELECT customer_id, order_date,
order_date - CAST(ROW_NUMBER() OVER (PARTITION BY customer_id
ORDER BY order_date) AS INT)
AS grp
FROM d
)
SELECT customer_id,
MIN(order_date) AS streak_start,
MAX(order_date) AS streak_end,
COUNT(*) AS streak_days
FROM grouped
GROUP BY customer_id, grp
HAVING COUNT(*) >= 3;SELECT
customer_id, order_id, order_date, channel,
FIRST_VALUE(channel) OVER (PARTITION BY customer_id
ORDER BY order_date, order_id) AS first_channel,
ROW_NUMBER() OVER (PARTITION BY customer_id
ORDER BY order_date, order_id) AS order_seq,
MIN(order_date) OVER (PARTITION BY customer_id) AS first_order_date,
SUM(amount) OVER (PARTITION BY customer_id
ORDER BY order_date, order_id
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW) AS ltv_to_date
FROM orders;Portability notes
| Feature | Where it works | Fallback |
|---|---|---|
| Core windows (ROW_NUMBER, RANK, LAG, SUM OVER, ROWS/RANGE frames) | Every major engine, including MySQL 8+ and SQLite 3.25+. | None needed. |
| QUALIFY | Snowflake, BigQuery, Databricks SQL, DuckDB, Teradata. | Wrap in a CTE or subquery and filter in the outer WHERE. |
| IGNORE NULLS on LAG / LEAD / FIRST_VALUE | Snowflake, BigQuery, Redshift, Oracle, Spark SQL. | A conditional running MAX over the non-null values. |
| GROUPS frame mode | PostgreSQL 11+, DuckDB. | Rewrite with RANGE, or pre-aggregate the peer groups. |
| EXCLUDE in a frame clause | PostgreSQL 11+, DuckDB. | Subtract the current row explicitly: SUM(x) OVER w - x. |
| Named WINDOW clause | PostgreSQL, MySQL 8+, Spark SQL, DuckDB and most others; a few engines still require the window inline. | Repeat the OVER (...) definition, or hide it in a CTE. |
| DISTINCT inside a window aggregate | Rejected by most engines, including PostgreSQL. | Pre-aggregate distinct values in a CTE, then window over the result. |
SQL Window Functions Cheatsheet · https://ctarunsai.github.io/cheatsheets/sql-window-functions/ · updated 28 Aug 2026 · Tarun Chitta
About this cheatsheet
A window function computes a value across a set of rows related to the current row, without collapsing those rows the way GROUP BY does. That single property — keeping the detail rows while also seeing their neighbours — is what makes running totals, rankings, period-over-period deltas and deduplication one-liners instead of self-joins.
Every window function reads the same three-part OVER clause. PARTITION BY splits the rows into independent groups; ORDER BY defines the sequence inside each group; the frame defines which rows around the current one are visible. Ranking and offset functions ignore the frame. Aggregate functions do not — and that difference is the source of the most common bug on this page, where LAST_VALUE returns the current row because the default frame ends there.
Every example below runs against one small table, so you can read the sheet top to bottom without re-learning the schema each time. The syntax is ANSI SQL and works unchanged on PostgreSQL, Spark SQL, Snowflake, BigQuery, Redshift, DuckDB and MySQL 8 unless a row says otherwise; the portability section at the end lists the extensions that do not travel.
One rule to internalise: window functions are evaluated *after* WHERE, GROUP BY and HAVING, and *before* ORDER BY and LIMIT. You cannot filter on a window result in the same WHERE clause that produced it — you need a subquery, a CTE, or QUALIFY on engines that support it.