Skip to content

Lesson 10 of 29Joining and aggregating

Window Functions

Rank, compare and accumulate across rows without collapsing them: OVER, PARTITION BY, frames, top-N per group and gaps and islands.

18 min read0/5 questions

Your product manager asks for three things before lunch: the two best-selling products in each category, how much each order changed the running revenue total, and which customers logged in several days in a row. With only GROUP BY, each of these turns into a self join or a pile of Python loops over exported rows. Window functions answer all three in one query each, inside the database, next to the data. They are also the single most tested topic in SQL interviews after joins, because they separate people who can write SELECT ... GROUP BY from people who can actually do analysis in SQL.

GROUP BY collapses, OVER keeps

In Aggregation, GROUP BY and HAVING you saw that GROUP BY department turns nine employee rows into two department rows. That is perfect for a summary, and useless when you want each employee and their department's average on the same line, so you can say "Mei earns 57k less than her department average".

A window function computes a value across a set of related rows, called the window, and writes the answer onto every row. Nothing is collapsed. You turn any aggregate into a window function by adding OVER (...).

Python
from shopdb import connect, showdb = connect()show(db, """SELECT department, name, salary, ROUND(AVG(salary) OVER (PARTITION BY department)) AS dept_avg, salary - ROUND(AVG(salary) OVER (PARTITION BY department)) AS vs_avgFROM employeesORDER BY department, salary DESC""")
Output
Press Run (⌘ Enter) to see what happens.

Nine rows in, nine rows out. PARTITION BY department splits the rows into groups the same way GROUP BY would, but each row keeps its identity and just gets the group's answer attached. Leave out PARTITION BY and the whole result is one partition: SUM(salary) OVER () puts the company-wide total on every row.

The three parts of a window

Every window definition has up to three parts, and each answers a different question.

  • PARTITION BY: which rows belong together? Calculations never cross a partition boundary.
  • ORDER BY: in what order are the rows of a partition walked? Ranking, LAG and running totals need it. A plain AVG over a whole department does not.
  • The frame: of the ordered rows, which ones count for this row? "Everything so far" gives a running total. "The previous six rows and this one" gives a seven-day moving average.

The ORDER BY inside OVER is independent of the query's final ORDER BY. The first decides how the window is computed. The second decides how the result is displayed. You will often want both, and they do not have to match.

When window functions run

Window functions are evaluated late, after FROM, WHERE, GROUP BY and HAVING, and just before DISTINCT, the final ORDER BY and LIMIT. That one fact explains most of the errors people hit.

Where windows sit in the logical order
  1. FROM and JOINbuild the rows
  2. WHEREfilter rows
  3. GROUP BY and HAVINGcollapse and filter groups
  4. Window functionscomputed over what is left
  5. SELECT list, DISTINCTpick and dedupe columns
  6. ORDER BY, LIMITsort and cut the output

WHERE runs before any window exists. That is why WHERE rn <= 3 fails: rn has not been computed yet.

1/3

Ranking: ROW_NUMBER, RANK and DENSE_RANK

The three ranking functions agree until there is a tie, and then they disagree in a way interviewers love to ask about. The products table has two items at 3900 cents.

Python
from shopdb import connect, showdb = connect()show(db, """SELECT name, price_cents, ROW_NUMBER() OVER (ORDER BY price_cents DESC, name) AS row_num, RANK() OVER (ORDER BY price_cents DESC) AS rnk, DENSE_RANK() OVER (ORDER BY price_cents DESC) AS denseFROM productsORDER BY price_cents DESC, name""")
Output
Press Run (⌘ Enter) to see what happens.
  • ROW_NUMBER gives every row a unique number: 1, 2, 3, even across ties. Which tied row gets 8 and which gets 9 is arbitrary unless you add a tie-breaker to the window's ORDER BY. Here name is the tie-breaker, so the result is repeatable.
  • RANK gives ties the same number and then skips: 8, 8, 10. It is the sports-table rank. "Joint eighth, and the next person is tenth."
  • DENSE_RANK gives ties the same number and does not skip: 8, 8, 9. Use it for "the third-highest distinct salary".

NTILE(n) splits the ordered rows into n buckets of near-equal size, which is handy for quartiles or "top third of customers by spend". PERCENT_RANK() and CUME_DIST() give a position between 0 and 1. The named WINDOW clause lets several functions share one definition, so you write the window once.

Python
from shopdb import connect, showdb = connect()show(db, """SELECT name, salary, NTILE(3) OVER w AS band, ROUND(PERCENT_RANK() OVER w, 2) AS pct_rankFROM employeesWINDOW w AS (ORDER BY salary)ORDER BY salary""")
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputSQL

What does this print?

-- scores: ana 90, ben 85, cy 85, dee 80
SELECT name,
     RANK()       OVER (ORDER BY score DESC) AS r,
     DENSE_RANK() OVER (ORDER BY score DESC) AS d
FROM scores;
-- What are r and d on dee's row?
Need a nudge? Hints walk you through it.

Top-N per group

"The two best-selling products in each category" is the most common window function task at work. You cannot put a window function in WHERE, because WHERE runs first. So you compute the rank in a CTE (or a subquery) and filter in the outer query.

Python
from shopdb import connect, showdb = connect()show(db, """WITH product_revenue AS ( SELECT c.name AS category, p.name AS product, SUM(oi.quantity * oi.unit_price_cents) AS revenue FROM order_items oi JOIN orders o ON o.id = oi.order_id JOIN products p ON p.id = oi.product_id JOIN categories c ON c.id = p.category_id WHERE o.status <> 'cancelled' GROUP BY c.name, p.name),ranked AS ( SELECT category, product, revenue, ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC, product) AS rn FROM product_revenue)SELECT category, product, revenue, rnFROM rankedWHERE rn <= 2ORDER BY category, rn""")
Output
Press Run (⌘ Enter) to see what happens.

Choose the ranking function on purpose. ROW_NUMBER returns exactly two per category even if the second and third place are tied. RANK or DENSE_RANK with <= 2 returns everyone tied for a place, so the count can be more than two. Ask which one the business wants. "Top two" usually means "show two cards on the page", which is ROW_NUMBER. "Everyone in the top two price levels" is DENSE_RANK.

Snowflake, BigQuery, Databricks and DuckDB have a QUALIFY clause that filters on a window function directly, like HAVING for windows. PostgreSQL does not, so in Postgres you always use the wrapper. Postgres also has two alternatives worth knowing:

-- Top 1 per group: DISTINCT ON keeps the first row of each group in sort order
SELECT DISTINCT ON (customer_id) customer_id, id, created_at
FROM orders
ORDER BY customer_id, created_at DESC;
 
-- Top N per group with an index on orders (customer_id, created_at DESC):
-- LATERAL runs a small indexed query per customer instead of ranking every order
SELECT c.id, recent.id AS order_id, recent.created_at
FROM customers c
CROSS JOIN LATERAL (
  SELECT id, created_at FROM orders o
  WHERE o.customer_id = c.id
  ORDER BY created_at DESC
  LIMIT 3
) AS recent;

The window version reads every row and sorts each partition. The LATERAL version can do a few index lookups per customer, which wins when partitions are large and N is small. Since Postgres 15, the planner can also stop computing a ROW_NUMBER partition early when the outer query filters on rn <= N, which closes some of that gap. Measure with EXPLAIN, which you will meet in Reading EXPLAIN.

LAG and LEAD: comparing a row with its neighbours

LAG(col) reads col from the previous row in the window. LEAD(col) reads it from the next row. Both take an optional offset and a default: LAG(total, 1, 0) returns 0 instead of NULL on the first row. This is how you get day-over-day change, time between events, or "did this user's status change since the last record?" without a self join.

Python
from shopdb import connect, showdb = connect()show(db, """SELECT user_id, kind, created_at, LAG(kind) OVER (PARTITION BY user_id ORDER BY created_at) AS previous_kind, ROUND((julianday(created_at) - julianday(LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at))) * 1440) AS minutes_since_prevFROM eventsWHERE user_id IN (1, 2)ORDER BY user_id, created_at""")
Output
Press Run (⌘ Enter) to see what happens.

The first row of each partition has no previous row, so LAG returns NULL. That is correct, and you should keep it: a NULL "minutes since previous event" means "first visit", which is different from zero. A product analyst would split sessions here: any gap over 30 minutes starts a new session.

Running totals and frames

Add an ORDER BY to an aggregate window and it becomes cumulative: SUM(total) OVER (ORDER BY created_at) is a running total. This is where the frame matters, and where most people get a wrong answer without noticing.

The frame says which rows, relative to the current row, feed the calculation. There are three frame types:

  • ROWS counts physical rows. ROWS BETWEEN 2 PRECEDING AND CURRENT ROW is exactly three rows.
  • RANGE works on the ORDER BY value. Rows with the same value (called peers) are always in or out together. RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW is "the last seven calendar days", however many rows that is.
  • GROUPS counts groups of peers. GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW is "this value and the previous distinct value".

The default-frame trap

If you write ORDER BY in a window and no frame, the SQL standard says the frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Because it is RANGE, all peers of the current row are included. When the ORDER BY has ties, every tied row gets the same running total, and the total "jumps" instead of growing one row at a time.

Python
from shopdb import connect, showdb = connect()show(db, """WITH order_totals AS ( SELECT o.id, substr(o.created_at, 1, 7) AS month, SUM(oi.quantity * oi.unit_price_cents) AS total FROM orders o JOIN order_items oi ON oi.order_id = o.id WHERE o.status <> 'cancelled' GROUP BY o.id)SELECT id, month, total, SUM(total) OVER (ORDER BY month) AS default_frame, SUM(total) OVER (ORDER BY month, id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rows_frame, LAST_VALUE(id) OVER (ORDER BY month) AS last_id_defaultFROM order_totalsORDER BY month, id""")
Output
Press Run (⌘ Enter) to see what happens.

Step through the first rows to see what each frame contains.

Which rows feed the running total
monthtotaldefaultROWS
order 12025-02199700
order 22025-028400
order 32025-0329900

Three orders sorted by month. Orders 1 and 2 share a month, so with ORDER BY month they are peers.

1/5

The same trap breaks LAST_VALUE. With the default frame, the frame ends at the current row (plus its peers), so LAST_VALUE(id) OVER (ORDER BY month) returns the current row's last peer, not the last row of the partition. To get the real last value, widen the frame to ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, or flip the sort and use FIRST_VALUE, which is simpler to read.

The rule seniors follow: whenever a window has ORDER BY and a frame-sensitive function (SUM, AVG, COUNT, LAST_VALUE, NTH_VALUE), write the frame explicitly, and make the ORDER BY unique. Ranking functions and LAG/LEAD ignore the frame, so they do not need one.

Quick check
A report uses SUM(amount) OVER (PARTITION BY account_id ORDER BY created_at::date) as a running balance. Customers complain that two payments on the same day show the same balance. What is the cause and the fix?
Need a nudge? A hint rules out a wrong answer.

Moving averages

A moving average smooths a noisy daily series. AVG(revenue) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) averages the current day and the six before it. Two caveats come up in code review. First, the first six rows average fewer than seven values, so the early points are less smooth; filter them out or show them faded. Second, ROWS counts rows, not days. If your daily table has missing days, seven rows can span ten calendar days. Either fill the gaps first (a calendar from a recursive CTE, as in Recursive CTEs and Hierarchies, left-joined to the data) or use RANGE with an interval in Postgres.

-- PostgreSQL: a true 7-calendar-day window, whatever rows exist
SELECT day, revenue,
       AVG(revenue) OVER (ORDER BY day
                          RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW) AS avg_7d
FROM daily_revenue;

Windows over aggregates: share of total

Because windows run after GROUP BY, you can wrap a group aggregate in a window aggregate. SUM(SUM(x)) OVER () reads as "the sum, over all groups, of each group's sum", which is the grand total. Divide by it and you get each group's share in one pass, without a second query for the total.

Python
from shopdb import connect, showdb = connect()show(db, """SELECT c.name AS category, SUM(oi.quantity * oi.unit_price_cents) AS revenue, ROUND(100.0 * SUM(oi.quantity * oi.unit_price_cents) / SUM(SUM(oi.quantity * oi.unit_price_cents)) OVER (), 1) AS pct_of_totalFROM order_items oiJOIN orders o ON o.id = oi.order_idJOIN products p ON p.id = oi.product_idJOIN categories c ON c.id = p.category_idWHERE o.status <> 'cancelled'GROUP BY c.nameORDER BY revenue DESC""")
Output
Press Run (⌘ Enter) to see what happens.

Note 100.0 rather than 100. Both engines do integer division on two integers, so 100 * 52200 / 664400 would truncate before you ever round.

Gaps and islands

"Find each customer's streaks of consecutive login days" sounds like it needs a loop. The classic trick: number each user's login days in order, then subtract that number of days from the date. Consecutive days move up by one at the same rate the row number does, so they all land on the same anchor date. A gap breaks the pattern and starts a new anchor. Group by the anchor and each group is one streak, or island.

Python
from shopdb import connect, showdb = connect()db.executescript("""INSERT INTO events (user_id, kind, created_at) VALUES (3, 'login', '2025-06-03 08:10'), (3, 'login', '2025-06-04 08:05'), (3, 'login', '2025-06-07 09:00'), (3, 'login', '2025-06-08 08:50'), (1, 'login', '2025-06-02 09:30'), (1, 'login', '2025-06-07 09:00');""")show(db, """WITH days AS ( SELECT DISTINCT user_id, date(created_at) AS day FROM events WHERE kind = 'login'),numbered AS ( SELECT user_id, day, date(day, '-' || ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) || ' days') AS anchor FROM days)SELECT user_id, MIN(day) AS streak_start, MAX(day) AS streak_end, COUNT(*) AS daysFROM numberedGROUP BY user_id, anchorHAVING COUNT(*) >= 2ORDER BY user_id, streak_start""")
Output
Press Run (⌘ Enter) to see what happens.

The DISTINCT in the first CTE matters: two logins on the same day would get two row numbers and break the arithmetic. In PostgreSQL the anchor is day - (ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day))::int, because subtracting an integer from a date gives a date. The same pattern finds runs of failed payments, periods when a server was down, or price ranges that stayed constant.

Match the pairs0/5 matched

Match each request to the window function that answers it.

Choose an item, then its match on the other side.

Performance and what happens underneath

A window function needs its rows sorted by the partition keys and then the ORDER BY keys. The planner usually adds a sort, then a WindowAgg node walks the sorted rows once, keeping a running state for the frame. For a running total that state is cheap: add the new row, and for a sliding ROWS frame, subtract the row that left. That makes most windows a single pass after the sort.

What costs you in practice:

  • The sort. On millions of rows it can spill to disk. An index on (partition_col, order_col) can provide rows already in order, and Postgres can then skip the sort.
  • Several different windows in one query. Each distinct PARTITION BY ... ORDER BY may need its own sort. Reuse one named WINDOW where you can.
  • Ranking everything to keep a few. If you only want the latest row per user, ROW_NUMBER over the whole table ranks every row. DISTINCT ON or LATERAL with an index may be much faster.

Window functions run in PostgreSQL, MySQL 8.0+, SQL Server, Oracle and SQLite 3.25+, so the syntax in this lesson is portable. The browser runs SQLite 3.39, which supports all three frame types, EXCLUDE, named windows and FILTER on window aggregates.

Put it in order6 steps

Put the steps in the order the database logically applies them to this query: SELECT ..., ROW_NUMBER() OVER (...) AS rn FROM orders WHERE status = 'paid' GROUP BY customer_id ORDER BY rn LIMIT 5

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Which query correctly keeps only the newest order per customer in PostgreSQL?
Need a nudge? A hint rules out a wrong answer.
Key terms
window function
A function computed across a set of rows related to the current row, written with OVER, that returns a value for every row instead of collapsing them.
partition
The group of rows a window is computed over, set by PARTITION BY. Calculations never cross partitions.
frame
The subset of the ordered partition, relative to the current row, that feeds a function like SUM or LAST_VALUE. Set with ROWS, RANGE or GROUPS.
peers
Rows with equal ORDER BY values in a window. RANGE and GROUPS frames always include or exclude peers together.
top-N per group
Ranking rows within each partition in a subquery or CTE, then filtering on the rank in the outer query.
gaps and islands
Finding runs of consecutive values by subtracting a row number from each value so that each run shares one anchor.
QUALIFY
A clause in Snowflake, BigQuery and DuckDB that filters on window results directly. PostgreSQL does not have it.