Window functions
Compute rankings, running totals and period-over-period changes.
By Invicly Tech, , in SQL & PostgreSQL. About 9 minutes to read.
In short
Window functions compute values across related rows without collapsing them. Each row keeps its identity but gains a rank, running total or previous value from its window, defined with OVER and PARTITION BY.
Explained simply
Sometimes you want a summary and the details at the same time. For example, a list of every order, plus the customer's total next to each one. GROUP BY cannot do that because it squashes the orders into one row. Window functions can.
Picture a class photo where each student also holds a card showing their rank in the class. Nobody leaves the photo; everyone just gets extra information about how they compare to the people around them. That is what a window function adds to each row.
The "window" is the set of rows each row looks at. OVER () means "all rows". OVER (PARTITION BY class) means "only my classmates". Adding ORDER BY inside OVER lets you ask ordered questions like "what was the value just before me?"
Window functions power many everyday reports: rankings, top 3 per category, running totals, moving averages, and change compared with last month. Once you know them, many long queries become short ones.
Press Play on a diagram to walk through it one step at a time.
- One row per group
- Detail rows are collapsed
- SUM(total) per customer
- Every row is kept
- Adds a value from the window
- Each order shows its customer's SUM
- Step 1PARTITION BY
Split rows into independent groups
- Step 2ORDER BY
Order rows within each partition
- Step 3Frame
Which nearby rows count, e.g. 6 preceding
- Step 4Function
ROW_NUMBER, SUM, LAG... computed per row
- 1, 2, 3, 4
- Always unique
- Ties broken arbitrarily
- Best for top N per group
- 1, 2, 2, 4
- Ties share a rank
- Leaves a gap after ties
- Like sports standings
- 1, 2, 2, 3
- Ties share a rank
- No gaps
- Good for "top 3 price levels"
In depth
The default frame trap
When OVER has an ORDER BY but no frame clause, Postgres uses RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. RANGE means rows with the same ORDER BY value are treated as one step. So if two sales share the same day, a running total shows the same combined value on both rows instead of growing row by row.
If you want strictly one row at a time, say so: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, or add a unique tie-breaker to ORDER BY.
Another surprise: LAST_VALUE(x) OVER (ORDER BY d) returns the current row's value, because the default frame ends at the current row. Use ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING to see the true last value.
- Default frame with ORDER BY: start to current row, ties grouped
- ROWS counts physical rows; RANGE groups equal values
- LAST_VALUE needs a frame to the end of the partition
- Day 1, 10: total 10
- Day 2, 5: total 22
- Day 2, 7: total 22
- Day 1, 10: total 10
- Day 2, 5: total 15
- Day 2, 7: total 22
When window functions run
Window functions are computed after FROM, WHERE, GROUP BY and HAVING, and just before the final ORDER BY and LIMIT. Two consequences follow.
First, you cannot filter on a window result in WHERE or HAVING, because it does not exist yet. Compute it in a CTE or subquery, then filter outside. Second, window functions can be applied to grouped results. SUM(SUM(amount)) OVER () looks odd, but the inner SUM is the GROUP BY aggregate and the outer SUM is a window over the grouped rows. That is how you compute each group's share of the total in one query.
- 1FROM, WHERE
Window results do not exist yet
- 2GROUP BY, HAVING
Still cannot filter on them
- 3Window functions
Can wrap aggregates: SUM(SUM(x)) OVER ()
- 4ORDER BY, LIMIT
Can use window results
- 5Need a filter?
Wrap in a CTE, filter outside
Naming windows and the full function family
If several columns use the same window, name it once: WINDOW w AS (PARTITION BY customer_id ORDER BY ordered_at), then write ROW_NUMBER() OVER w, SUM(total) OVER w.
The main families: ranking (ROW_NUMBER, RANK, DENSE_RANK, NTILE(4) for quartiles, PERCENT_RANK), offset (LAG, LEAD, FIRST_VALUE, LAST_VALUE, NTH_VALUE), and any normal aggregate (SUM, AVG, COUNT, MIN, MAX) used with OVER. LAG(x, 1, 0) takes the value one row back and uses 0 instead of NULL for the first row.
Cost and indexes
To compute a window, Postgres sorts the rows by the PARTITION BY and ORDER BY columns, then walks them in order. On large tables that sort is the main cost. An index that already matches, such as (customer_id, ordered_at) for PARTITION BY customer_id ORDER BY ordered_at, lets Postgres read rows in order and skip the sort.
Several window functions with the same window share one sort. Functions with different windows each need their own sort, so use as few distinct windows as you can.
Learn it in 5 short steps
About 1h each. Track them with a timer in your plan.
- 1Use OVER and PARTITION BY~1h
- 2Rank rows with ROW_NUMBER and RANK~1h
- 3Compute running totals~1h
- 4Compare periods with LAG and LEAD~1h
- 5Use frame clauses for moving averages~1h
Key points
- ROW_NUMBER gives unique numbers; RANK leaves gaps after ties; DENSE_RANK does not.
- SUM(x) OVER (ORDER BY day) gives a running total.
- LAG(x) reads the previous row's value; LEAD(x) reads the next one.
- Window functions cannot go in WHERE; filter them in an outer query or CTE.
Key terms
Tap a card to flip it. 0/5 known
Examples
SELECT
day,
revenue,
SUM(revenue) OVER (ORDER BY day) AS running_total,
revenue - LAG(revenue) OVER (ORDER BY day) AS change_vs_prev,
AVG(revenue) OVER (ORDER BY day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS avg_7d
FROM daily_sales;
-- top 3 products per category
SELECT * FROM (
SELECT p.*, ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) AS rn
FROM products p
) t
WHERE rn <= 3;Month-over-month growth
Step 1: in a CTE, total revenue per month. Step 2: LAG(revenue) brings last month's value onto this month's row. Step 3: compute the change and the percentage; NULLIF avoids division by zero. The first month shows NULL growth because it has no previous month, which is honest.
WITH monthly AS (
SELECT date_trunc('month', ordered_at) AS month, SUM(total) AS revenue
FROM orders WHERE status = 'paid'
GROUP BY 1
)
SELECT month, revenue,
LAG(revenue) OVER (ORDER BY month) AS prev,
round(100 * (revenue - LAG(revenue) OVER (ORDER BY month))
/ NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 1) AS growth_pct
FROM monthly
ORDER BY month;Spotting each customer's first order
Marketing wants to know which orders were a customer's first. Step 1: number each customer's orders by date with ROW_NUMBER, partitioned by customer. Step 2: add the customer's lifetime order count with COUNT(*) over the same partition, without an ORDER BY so the frame is the whole partition. Step 3: is_first is just rn = 1. Every order row stays in the output.
SELECT id, customer_id, ordered_at,
ROW_NUMBER() OVER w = 1 AS is_first,
COUNT(*) OVER (PARTITION BY customer_id) AS lifetime_orders
FROM orders
WINDOW w AS (PARTITION BY customer_id ORDER BY ordered_at, id)
ORDER BY customer_id, ordered_at;Quick reference
- fn() OVER (PARTITION BY g ORDER BY x ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
- Filter on a window result in an outer query: WHERE rn <= 3
- Share of total: x / SUM(x) OVER ()
- LAG(x, 1, 0) OVER (ORDER BY d): previous value, 0 for the first row
- NTILE(4) OVER (ORDER BY score): split rows into quartiles
- WINDOW w AS (...) to reuse one window definition
- Use ROWS, not the default RANGE, for row-by-row running totals with ties
Common mistakes
- Trying to use a window function in WHERE.
- Default frame with ORDER BY includes tied rows, surprising running totals.
- Forgetting PARTITION BY, so ranks span the whole table.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
From employees(name, department, salary), show each employee with the average salary of their department next to them.
- Exercise 2medium
Show the 2 highest-paid employees in each department.
- Exercise 3hard
From daily_sales(day, revenue), show each day with a 7-day moving average and flag days more than 50% above that average.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between PARTITION BY and GROUP BY?
- Both split rows into groups. GROUP BY returns one row per group, while PARTITION BY keeps every row and only uses the group for the window calculation.
- Can I use a window function inside an aggregate?
- No, but you can do it the other way round: an aggregate inside a window, such as SUM(SUM(x)) OVER (). For the reverse, compute the window in a CTE and aggregate outside.
- Do window functions work in MySQL and other databases?
- Yes. They are standard SQL and are supported by MySQL 8+, SQL Server, Oracle and SQLite, with only small differences.