Sub topic 13
When to Use a Window Function Instead
This chapter assumes you can write a GROUP BY query with COUNT, SUM and AVG. You should also know how WHERE and HAVING differ, and what a LEFT JOIN does. It does not teach window functions in full. It shows when a window function fits better than GROUP BY, and how to tell the two apart.
The core difference
GROUP BY collapses rows. If 500 orders belong to 40 customers, a grouped query returns 40 rows, and the individual orders are gone from the result.
A window function computes the same kind of summary but keeps every input row. Each row gets the summary value attached as an extra column. The OVER clause is what marks a function as a window function.
SELECT order_id,
customer_id,
amount,
SUM(amount) OVER (PARTITION BY customer_id) AS customer_total
FROM orders;This query returns one row per order. Each row also shows the total for its customer. Two orders from customer 7 both show the same customer_total.
The grouped version of the same total looks like this:
SELECT customer_id,
SUM(amount) AS customer_total
FROM orders
GROUP BY customer_id;It returns one row per customer, and the order-level columns are no longer available.
Reading the OVER clause
A window function has the form function(...) OVER (window specification). The window specification can contain:
PARTITION BY, which splits the rows into groups. It plays the role thatGROUP BYplays, but it does not collapse anything. If you omit it, the whole result set is one partition.ORDER BY, which orders rows inside each partition. It is needed for running totals and rankings.- A frame clause such as
ROWS BETWEEN ..., which limits which rows in the partition each calculation sees. It is optional.
The aggregate functions you already know (COUNT, SUM, AVG, MIN, MAX) all work as window functions when you add OVER. They also follow the same NULL rules: SUM, AVG, MIN, MAX and COUNT(column) skip NULL values, and COUNT(*) counts every row.
When a window function is the better fit
Use a window function when the result must keep row-level detail next to a summary. Common cases are listed below.
Comparing each row with its group
You want each order next to the share it makes up of the customer's total:
SELECT order_id,
customer_id,
amount,
amount * 100.0 / SUM(amount) OVER (PARTITION BY customer_id) AS pct_of_customer
FROM orders;With GROUP BY alone, you would have to compute the totals in a subquery and join them back to orders. The window version does this in one pass over the query.
Running totals
A running total needs an ordering, so the window gets an ORDER BY:
SELECT customer_id,
order_id,
amount,
SUM(amount) OVER (
PARTITION BY customer_id
ORDER BY order_id
) AS running_total
FROM orders;GROUP BY cannot express this at all, because each row needs a different subset of the data.
Ranking within a group
Functions such as ROW_NUMBER() and RANK() exist only as window functions. They answer questions such as "which is each customer's largest order?":
SELECT customer_id, order_id, amount
FROM (
SELECT customer_id,
order_id,
amount,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY amount DESC
) AS rn
FROM orders
) AS ranked
WHERE rn = 1;Notice the subquery. The next section explains why it is required.
When GROUP BY is the better fit
Use GROUP BY when you want a summary table and do not need the detail rows. Reports like "revenue per month" or "orders per customer" want exactly one row per group. A window function would return the same total repeated on every detail row, and you would then have to remove the duplicates with DISTINCT. That is slower and harder to read.
GROUP BY also supports HAVING, which filters on the summary value directly. Window functions have no equivalent keyword.
| Need | Better tool |
|---|---|
| One row per group | `GROUP BY` |
| Filter groups by their total | `GROUP BY` with `HAVING` |
| Detail rows plus a group total | Window function |
| Share of total, difference from average | Window function |
| Running total or moving average | Window function |
| Rank or row number within a group | Window function |
| Subtotals and a grand total | `ROLLUP` or `GROUPING SETS` |
Where window functions sit in the evaluation order
In the logical order of evaluation, window functions run after GROUP BY and HAVING, and just before SELECT's final output and ORDER BY. This has two practical consequences.
First, you cannot put a window function in WHERE. WHERE runs before the window values exist. This query fails:
SELECT order_id, amount
FROM orders
WHERE SUM(amount) OVER (PARTITION BY customer_id) > 1000;The fix is to compute the window value in a subquery or common table expression (CTE) and filter in the outer query:
WITH totals AS (
SELECT order_id,
amount,
SUM(amount) OVER (PARTITION BY customer_id) AS customer_total
FROM orders
)
SELECT order_id, amount
FROM totals
WHERE customer_total > 1000;This is also why the ranking example above needed a subquery to filter on rn = 1.
Second, a window function sees only the rows that survived WHERE. If WHERE status = 'paid' removes unpaid orders, a window total computed in the same query covers only paid orders.
Mixing GROUP BY and window functions
You can use both in one query. The window function then operates on the grouped result, so it can reference only grouped columns and aggregates. For example, this ranks customers by their total:
SELECT customer_id,
SUM(amount) AS total_amount,
RANK() OVER (ORDER BY SUM(amount) DESC) AS spend_rank
FROM orders
GROUP BY customer_id;GROUP BY first produces one row per customer. Then RANK() orders those rows by the total. The expression SUM(amount) inside OVER is legal because aggregation has already happened.
Gotchas
- Default frame with ORDER BY. When a window has an
ORDER BYand no frame clause, most databases useRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Rows that tie on the ordering column are treated as peers and get the same running total. In the running-total example, ties onorder_idcannot happen because it is unique. If you order by a column such asorder_date, two orders on the same date show the same running value. AddROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWor a unique tie-breaker column to get a strict row-by-row total. - Repeated values are not extra data. Summing a window total across detail rows multiplies it. If
customer_totalappears on three rows,SUM(customer_total)counts it three times. - Distinct counts. Many databases do not allow
COUNT(DISTINCT ...)as a window function. PostgreSQL, for example, rejects it. Compute it withGROUP BYin a subquery instead. - Performance. A window function sorts or hashes the data by the partition key. On large tables this can cost more than a plain
GROUP BY, especially when you only needed one row per group. - Support. Window functions are standard in modern PostgreSQL, SQL Server, Oracle, MySQL 8.0 and later, and SQLite 3.25 and later. Older MySQL versions do not have them.
Checking your result
A quick check helps when you switch between the two approaches:
- Count the rows. A grouped query should return as many rows as there are distinct groups. A window query should return as many rows as the input has after
WHEREand joins. - Compare totals. Take one customer and run both the grouped and the window version. The
customer_totalvalues should match. - Check for NULLs. If a
PARTITION BYcolumn is NULL, all NULL rows form one partition, the same asGROUP BYputs them in one group.
Exercise
The orders table has columns orderid, customerid and amount. Write a query that returns every order together with the average order amount for that order's customer, and a column showing how far the order is above or below that average.
Show answer
SELECT orderid, customerid, amount, AVG(amount) OVER (PARTITION BY customerid) AS customeravg, amount - AVG(amount) OVER (PARTITION BY customerid) AS difffrom_avg FROM orders; A window function is needed because each output row must keep its own amount next to the customer-level average. GROUP BY would return only one row per customer.
Exercise
A colleague writes SELECT customerid, SUM(amount) FROM orders WHERE SUM(amount) OVER (PARTITION BY customerid) > 1000 GROUP BY customer_id. It fails. Give two reasons, and rewrite it to return customers whose total is above 1000.
Show answer
First, window functions cannot appear in WHERE, because WHERE is evaluated before window values exist. Second, the query already groups by customer, so the window function is unnecessary. Use HAVING: SELECT customerid, SUM(amount) AS totalamount FROM orders GROUP BY customer_id HAVING SUM(amount) > 1000;
Exercise
You want each customer's most recent order, one row per customer, and the table has an order_date column. Which feature do you use, and why can you not filter on it in the same SELECT?
Show answer
Use ROWNUMBER() OVER (PARTITION BY customerid ORDER BY order_date DESC) in a subquery or CTE, then filter WHERE rn = 1 in the outer query. The filter cannot go in the same SELECT because WHERE is evaluated before window functions, so the rn column does not exist yet at that point.