Skip to content
Commitwise
Menu
Databases

Window functions: ranking, running totals and LAG

Aggregates that keep every row with OVER and PARTITION BY, ROW_NUMBER vs RANK vs DENSE_RANK, top N per group, deleting duplicates, running totals that jump on ties, LAG and LEAD, moving averages, and the gaps-and-islands login streak. The SQL that separates mid-level from senior answers.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

“Each order, and what share of that customer’s spending it was.” “The three best-selling products in each category.” “Revenue per day, and the change from the day before.” With GROUP BY alone each of these takes a subquery and a self-join, and reads like a puzzle.

Window functions answer them in one pass. They compute over a group of rows like an aggregate, but keep every row in the result. They’re also the favorite topic of SQL interviews past the junior level: “top N per group”, “second highest salary”, “consecutive days” are all window function questions. The examples use the shop tables from How relational databases work.

New to some of these? Open what you need, or skip ahead.

Basics:GROUP BY and aggregates

count, sum, avg, min and max turn many rows into one value; GROUP BY gives one row per group; HAVING filters groups. WHERE runs before grouping, so it can’t use avg(…). See Aggregation.

Basics:Subqueries and WITH

A query in parentheses can be used as a table: FROM (SELECT …) AS t. WITH name AS (…) names such a step so the main query can use it. See Subqueries and CTEs.

Part Not started

OVER: aggregates that keep every row

GROUP BY squashes each group into one row. Sometimes you want the group’s total and every row. “Each order, next to the customer’s total”:

SELECT id,
       customer_id,
       total,
       sum(total) OVER (PARTITION BY customer_id) AS customer_total
FROM orders;
idcustomer_idtotalcustomer_total
1012050
1113050
1221515

OVER (…) is what makes it a window functionWindow functionA SQL function computed over a set of related rows with OVER, keeping every row in the result.Open in glossary →:

  • OVER () with nothing inside: the window is all rows. sum(total) OVER () puts the grand total on every row.
  • OVER (PARTITION BY customer_id): the window is the rows with the same customer as the current row. Like GROUP BY, but the rows stay.

Every aggregate works this way: count(*) OVER (…), avg(…) OVER (…), max(…) OVER (…).

Window functions are computed late, after WHERE, GROUP BY and HAVING, right where SELECT runs. So you can’t use one in WHERE. To filter on it, compute it in a subquery or CTE, then filter outside:

WITH t AS (
    SELECT id, customer_id, total,
           avg(total) OVER (PARTITION BY customer_id) AS customer_avg
    FROM orders
)
SELECT * FROM t WHERE total > 2 * customer_avg;   -- unusually big orders
  • Evaluation order: FROM → WHERE → GROUP BY → HAVING → window functions → SELECT list → DISTINCT → ORDER BY → LIMIT. Hence: no windows in WHERE/HAVING; they see rows after WHERE; and you can window over aggregates: sum(sum(total)) OVER () gives a grand total next to grouped rows, sum(total) / sum(sum(total)) OVER () a share.
  • Filtering: a subquery or CTE. Snowflake, BigQuery, DuckDB and Databricks have QUALIFY; PostgreSQL, MySQL and SQL Server don’t.
  • Anatomy: fn(args) OVER (PARTITION BY … ORDER BY … frame). Reuse with WINDOW w AS (PARTITION BY customer_id ORDER BY created_at) and OVER w.
  • Execution: a WindowAgg node over input sorted by partition and order keys. An index on (partition_col, order_col) can provide the order; several different windows in one query may mean several sorts.
  • Support: PostgreSQL 8.4+, MySQL 8.0+, SQL Server, Oracle, SQLite 3.25+. On Android the bundled SQLite reached 3.25+ only around API 30, so Room queries with OVER need a recent minSdk or a bundled SQLite; iOS has had it for years.

Predict the output

orders has 5 rows from 2 customers. How many rows does each query return?

SELECT customer_id, sum(total)
FROM orders
GROUP BY customer_id;

SELECT customer_id, sum(total) OVER (PARTITION BY customer_id)
FROM orders;
SELECT id,
       customer_id,
       total,
       round(100.0 * total / sum(total) OVER (PARTITION BY customer_id), 1) AS pct_of_customer,
       round(100.0 * total / sum(total) OVER (), 2)                         AS pct_of_all,
       total - avg(total) OVER (PARTITION BY customer_id)                  AS vs_customer_avg
FROM orders
WHERE status = 'PAID';

-- window over an aggregate: each country's share of all customers
SELECT country,
       count(*) AS customers,
       round(100.0 * count(*) / sum(count(*)) OVER (), 1) AS pct
FROM customers
GROUP BY country;

Worked example: a partition, row by row

Five paid orders:

idcustomer_idtotal
10120
11130
12150
13240
14210

We want round(100.0 * total / sum(total) OVER (PARTITION BY customer_id)): each order’s share of its customer’s spending.

  1. Split into partitions. Customer 1: orders 10, 11, 12. Customer 2: orders 13, 14. Nothing is removed.
  2. Compute the window sum per partition. Customer 1: 20 + 30 + 50 = 100. Customer 2: 40 + 10 = 50.
  3. Put it on every row of its partition. Orders 10, 11 and 12 see 100; orders 13 and 14 see 50.
  4. Finish the expression per row. Order 10: 100 × 20 / 100 = 20%. Order 11: 30%. Order 12: 50%. Order 13: 80%. Order 14: 20%.
  5. Result: five rows, each with its own percentage. With GROUP BY you’d have needed the totals in a subquery and a join back to orders.
Deep diveWhy you can't filter on a window function in WHERE, and what to do insteadInterview favorite

SELECT …, row_number() OVER (…) AS rn FROM t WHERE rn = 1 fails with “column rn does not exist”, and writing the function itself in WHERE fails with “window functions are not allowed in WHERE”. The reason is the evaluation order: WHERE decides which rows exist before windows are computed, and a window’s value depends on which rows exist. Filtering on it in WHERE would be circular.

The options:

  • Subquery or CTE, then filter. The standard answer, works everywhere.
  • QUALIFY in Snowflake, BigQuery, DuckDB, Databricks: … QUALIFY row_number() OVER (…) = 1. Mention it, but don’t use it in a PostgreSQL interview.
  • DISTINCT ON in PostgreSQL for “first row per group”: SELECT DISTINCT ON (customer_id) * FROM orders ORDER BY customer_id, created_at DESC.
  • LATERAL … LIMIT n for top-N per group when there’s a good index and few groups.

A subtle follow-up: filters in the outer query don’t change the window, while filters inside do. “Share of the customer’s total” computed over all orders, then filtered to November, still divides by the all-time total; filtering to November inside the CTE divides by the November total. Decide which question you’re answering before choosing.

  • fn() OVER (PARTITION BY … ORDER BY … frame): aggregate per window, rows kept. WINDOW w AS (…) for reuse.
  • Evaluated after HAVING, before ORDER BY/LIMIT: no windows in WHERE; filter in an outer query (QUALIFY only in Snowflake/BigQuery/DuckDB).
  • Windows over aggregates: sum(count(*)) OVER (). Inner vs outer filters change the denominator.
  • SQLite 3.25+ (Android: recent API levels), MySQL 8.0+.
SELECT customer_id, id, total,
       sum(total) OVER w AS customer_total,
       round(100.0 * total / sum(total) OVER w, 1) AS pct
FROM orders
WINDOW w AS (PARTITION BY customer_id);

Check this part

  1. How is sum(total) OVER (PARTITION BY customer_id) different from GROUP BY customer_id?

  2. What window does OVER () cover?

  3. How do you keep only rows where a window function equals 1 in PostgreSQL?

  4. What does sum(count(*)) OVER () compute in a GROUP BY country query?

A window function computes over related rows but keeps every row: sum(total) OVER (PARTITION BY customer_id) puts each customer's total next to each of their orders. Window functions run after WHERE, GROUP BY and HAVING, so you filter on them in an outer query.

Part Not started

Ranking: ROW_NUMBER, RANK and DENSE_RANK

Put ORDER BY inside OVER, and the window function can number the rows in that order. Three functions do it, and they only differ on ties:

scorerow_number()rank()dense_rank()
95111
90222
90322
80443
  • row_number(): always 1, 2, 3, 4. Ties get different numbers, in no particular order.
  • rank(): ties share a number, and the next number is skipped (like sports: two silver medals, no bronze).
  • dense_rank(): ties share a number, no gaps.

Add PARTITION BY and the numbering restarts for each group. That’s the classic top N per group: the three best-selling products in each category.

WITH sales AS (
    SELECT p.category, p.name, sum(oi.quantity) AS units
    FROM order_items oi
    JOIN products p ON p.id = oi.product_id
    GROUP BY p.category, p.name
),
ranked AS (
    SELECT *, row_number() OVER (PARTITION BY category ORDER BY units DESC, name) AS rn
    FROM sales
)
SELECT category, name, units
FROM ranked
WHERE rn <= 3
ORDER BY category, rn;

ORDER BY units DESC, name: when two products sold the same number, name decides, so the result is the same every time you run it.

  • Choosing: row_number for “exactly N” and deduplication; rank when ties should share a place and push the next down (“top 3” may return 4); dense_rank for “Nth distinct value” (“second highest salary”: dense_rank() = 2).
  • Determinism: row_number over non-unique keys picks arbitrarily and can change between runs and plans. Always end the window’s ORDER BY with a unique column.
  • Other ranking functions: ntile(4) (quartiles), percent_rank(), cume_dist().
  • Top-N per group, options: row_number in a subquery (one sort of everything; best when you need it for all groups), LATERAL … ORDER BY … LIMIT n (an index probe per group; best for few groups or a page of them), PostgreSQL DISTINCT ON for N = 1. When the partition and order columns are stored and indexed (say (category_id, created_at DESC)), the window can skip the sort, but it still reads all rows: there’s no per-partition LIMIT pushdown in PostgreSQL.
  • “Second highest salary” (the most asked SQL interview question): dense_rank in a subquery, or SELECT max(salary) FROM e WHERE salary < (SELECT max(salary) FROM e), or … ORDER BY salary DESC OFFSET 1 LIMIT 1 over DISTINCT salary. Discuss ties and “no second value → NULL”.

Predict the output

Three players have scores 90, 90 and 80. What do rank() and dense_rank() give the player with 80?

SELECT player, score,
       rank()       OVER (ORDER BY score DESC) AS rnk,
       dense_rank() OVER (ORDER BY score DESC) AS dense
FROM scores;
-- each customer's orders numbered from the newest
SELECT customer_id, id, created_at,
       row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC, id DESC) AS nth_latest
FROM orders;

-- the second highest product price (NULL if there's only one price)
SELECT max(price) AS second_highest
FROM (SELECT price, dense_rank() OVER (ORDER BY price DESC) AS r FROM products) t
WHERE r = 2;

The filter that comes too early

Spot the bugEach customer's latest order

Tap the line with the bug.

SELECT customer_id,
       id,
       created_at,
       row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn
FROM orders
WHERE rn = 1;

Deep diveDeleting duplicates and keeping the newestInterview favorite

A sync bug inserted the same device token several times per user. You need to keep one row per (user_id, token), the most recently updated, and delete the rest, then add the unique constraint that should have been there.

WITH ranked AS (
    SELECT id,
           row_number() OVER (PARTITION BY user_id, token
                              ORDER BY updated_at DESC, id DESC) AS rn
    FROM device_tokens
)
DELETE FROM device_tokens d
USING ranked r
WHERE d.id = r.id
  AND r.rn > 1;

ALTER TABLE device_tokens ADD CONSTRAINT device_tokens_user_token_key UNIQUE (user_id, token);

What a strong answer adds:

  • Check first: run the CTE with SELECT count(*) … WHERE rn > 1 and look at a sample before deleting.
  • Concurrency: while the delete runs, the bug keeps inserting. Fix the writer (use an upsert, ON CONFLICT), or add the constraint as CREATE UNIQUE INDEX CONCURRENTLY right after cleanup and retry if a new duplicate sneaks in.
  • Size: millions of duplicates → delete in batches by id range.
  • Merge, don’t just drop: if duplicates carry different data (one has a newer last_seen), compute the merged values first; row_number only decides who survives.
  • Alternative without windows: DELETE FROM t a USING t b WHERE a.user_id = b.user_id AND a.token = b.token AND (a.updated_at, a.id) < (b.updated_at, b.id). Correct, but a self-join that’s slower on big groups.
  • row_number 1,2,3 (arbitrary on ties), rank 1,1,3, dense_rank 1,1,2. Add a unique tiebreaker to the window ORDER BY.
  • Top N per group: row_number in a CTE + WHERE rn <= N; LATERAL … LIMIT for few groups; DISTINCT ON for N = 1.
  • Second highest: dense_rank() = 2 (handles ties; NULL when missing).
  • Dedup: row_number() OVER (PARTITION BY key ORDER BY newest) → delete rn > 1, then add the unique constraint.

Check this part

  1. Scores 90, 90, 80. What does row_number() OVER (ORDER BY score DESC) give?

  2. What does PARTITION BY category do to row_number()?

  3. Which function answers "the second highest salary" correctly when the top salary is shared?

  4. Why add id to ORDER BY created_at inside a row_number() window?

ORDER BY inside OVER numbers rows: row_number gives 1, 2, 3 even on ties, rank gives 1, 1, 3, dense_rank gives 1, 1, 2. Top N per group = row_number over a partition, then filter rn <= N outside. Add a tiebreaker for repeatable results. row_number also finds duplicates to delete.

Part Not started

Running totals, LAG and moving averages

ORDER BY inside OVER also changes what an aggregate adds up: from the first row up to the current row. That’s a running total:

SELECT day,
       revenue,
       sum(revenue) OVER (ORDER BY day) AS running_total
FROM daily_revenue;
dayrevenuerunning_total
Nov 1100100
Nov 280180
Nov 3120300

Two functions look at neighbors:

  • lag(revenue): the value from the previous row. NULL on the first row, which has none.
  • lead(revenue): the value from the next row.

“Change from the day before” is revenue - lag(revenue) OVER (ORDER BY day).

You can also say exactly which rows to include, with a frame. A 7-day moving average takes the current row and the 6 before it:

avg(revenue) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)

The first six days average fewer than 7 values, because there aren’t 6 rows before them yet.

  • Default frame: with ORDER BY and no frame, it’s RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. RANGE includes all peers (rows with the same ORDER BY value), so two orders at the same timestamp both show the total including both: the running total jumps by two at once. Use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW or a unique tiebreaker. Without ORDER BY, the frame is the whole partition.
  • last_value trap: under the default frame it returns the current row (the frame ends there). Use ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, or first_value with the opposite order. nth_value has the same issue.
  • Time-based frames: ROWS 6 PRECEDING means 6 rows, not 6 days; with missing days it spans more. PostgreSQL 11+ supports RANGE BETWEEN interval '6 days' PRECEDING AND CURRENT ROW over a date/timestamp, or fill the calendar first with generate_series.
  • lag(x, n, default) takes an offset and a default; IGNORE NULLS exists in Oracle and Snowflake (SQL Server 2022 has it for first_value/last_value), not in PostgreSQL.
  • GROUPS frames (PostgreSQL 11+) count peer groups, and EXCLUDE CURRENT ROW makes “average of the others” easy.
  • Gaps and islands: consecutive sequences (login streaks, uptime periods, runs of the same status) via day - row_number() (below) or lag + a running sum of “new group starts here” flags.

Predict the output

Orders: 10 at 09:00, 20 at 09:05, 30 at 09:05 (same second). What running totals does this show?

SELECT created_at, total,
       sum(total) OVER (ORDER BY created_at) AS running
FROM orders
WHERE created_at::date = date '2026-11-14';
WITH daily AS (
    SELECT created_at::date AS day, sum(total) AS revenue
    FROM orders
    WHERE status = 'PAID'
    GROUP BY 1
)
SELECT day,
       revenue,
       revenue - lag(revenue) OVER (ORDER BY day)                       AS change,
       sum(revenue) OVER (ORDER BY day ROWS UNBOUNDED PRECEDING)       AS running_total,
       round(avg(revenue) OVER (ORDER BY day ROWS 6 PRECEDING), 2)      AS moving_avg_7
FROM daily
ORDER BY day;

-- time between a customer's consecutive orders
SELECT customer_id, id, created_at,
       created_at - lag(created_at) OVER (PARTITION BY customer_id ORDER BY created_at) AS since_previous
FROM orders;

Practice: day-over-day change

Exercisemedium

Revenue compared with the day before

Using a daily_revenue(day, revenue) table with one row per day, return each day with its revenue, the previous day’s revenue, and the change in percent, rounded to one decimal. The first day has no previous day; show NULL there.

›

lag(revenue) OVER (ORDER BY day) gives the previous day’s revenue on each row.

›

Percent change is 100.0 * (today - yesterday) / yesterday. What happens if yesterday’s revenue is 0? NULLIF(x, 0) turns 0 into NULL.

SolutionTry it yourself first
SELECT day,
       revenue,
       lag(revenue) OVER (ORDER BY day) AS previous,
       round(100.0 * (revenue - lag(revenue) OVER (ORDER BY day))
                   / NULLIF(lag(revenue) OVER (ORDER BY day), 0), 1) AS change_pct
FROM daily_revenue
ORDER BY day;

On the first day lag is NULL, so the whole calculation is NULL, which is what we want. NULLIF avoids a “division by zero” error after a day with no sales. Repeating lag(…) three times is fine (the database computes the window once); a WINDOW w AS (ORDER BY day) clause or a CTE would make it shorter.

Deep diveGaps and islands: the longest login streakInterview favorite

logins(user_id, day) has one row per user per day they used the app. “Each user’s longest streak of consecutive days” is the classic gaps and islands problem.

The trick: number each user’s days in order. Within a run of consecutive days, the date and the row number both go up by 1, so date minus row number is constant for the whole run, and changes after every gap.

dayrow_numberday - row_number
Nov 11Oct 31
Nov 22Oct 31
Nov 33Oct 31
Nov 74Nov 3
Nov 85Nov 3
WITH numbered AS (
    SELECT user_id, day,
           day - row_number() OVER (PARTITION BY user_id ORDER BY day)::int AS island
    FROM (SELECT DISTINCT user_id, day FROM logins) d
),
streaks AS (
    SELECT user_id, island, count(*) AS length, min(day) AS start_day, max(day) AS end_day
    FROM numbered
    GROUP BY user_id, island
)
SELECT DISTINCT ON (user_id) user_id, length, start_day, end_day
FROM streaks
ORDER BY user_id, length DESC, end_day DESC;

Points to call out: DISTINCT user_id, day first, because two logins on one day would break the arithmetic; date - integer is a date in PostgreSQL (use DATEADD/INTERVAL elsewhere); the “current streak” is the island whose end_day is today or yesterday. The general version of the technique, for runs that aren’t defined by consecutive integers (status changes, sessions with a 30-minute timeout), uses lag to flag where a new group starts and a running sum of the flags as the group id:

sum(CASE WHEN ts - lag(ts) OVER w > interval '30 minutes' THEN 1 ELSE 0 END) OVER w
  • ORDER BY in OVER → running aggregates. Default frame = RANGE … CURRENT ROW (includes ties): use ROWS or a unique tiebreaker.
  • lag/lead(x, n, default); last_value needs UNBOUNDED FOLLOWING.
  • ROWS 6 PRECEDING = 6 rows, not 6 days: fill the calendar or use RANGE interval '6 days' PRECEDING.
  • Gaps and islands: day - row_number() per user, or lag flags + running sum as group id.
SELECT day, revenue,
       revenue - lag(revenue) OVER w                           AS change,
       sum(revenue) OVER (w ROWS UNBOUNDED PRECEDING)          AS running,
       avg(revenue) OVER (w ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma7
FROM daily_revenue
WINDOW w AS (ORDER BY day);

Check this part

  1. What does sum(revenue) OVER (ORDER BY day) compute?

  2. What does lag(revenue) return on the first row?

  3. Why can a running total with ORDER BY created_at jump by two orders at once?

  4. How do you find runs of consecutive days per user?

With ORDER BY inside OVER, aggregates become running totals; lag and lead read the previous or next row. A frame like ROWS BETWEEN 6 PRECEDING AND CURRENT ROW makes a moving average. The default frame includes ties (RANGE), so running totals jump on equal values; use ROWS. Gaps-and-islands groups consecutive rows.

Key takeaways

  • fn() OVER (PARTITION BY …) computes per group but keeps every row; OVER () covers all rows.
  • Window functions run after WHERE: compute them in a CTE and filter outside.
  • row_number 1, 2, 3; rank 1, 1, 3; dense_rank 1, 1, 2. Top N per group = row_number + WHERE rn <= N outside.
  • sum(…) OVER (ORDER BY day) is a running total; lag and lead read neighbors; ROWS BETWEEN 6 PRECEDING AND CURRENT ROW is a moving window.
  • Add a unique column to the window’s ORDER BY so results repeat exactly.
  • Evaluation order explains every “can’t use it here”: windows after HAVING, before ORDER BY/LIMIT; windows over aggregates work.
  • Top-N per group: row_number, LATERAL … LIMIT, DISTINCT ON; dedup with row_number then a unique constraint.
  • Default RANGE frame includes peers; last_value needs an explicit frame; row frames aren’t time frames.
  • Gaps and islands with day - row_number() or lag flags plus a running sum.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.