Sub topic 8
Where window functions run and how to filter on them
This chapter assumes you can write SELECT, WHERE, GROUP BY and HAVING queries, use CTEs and subqueries, and read a basic OVER (PARTITION BY ... ORDER BY ...) clause. The aim is to explain why window functions fail in some clauses and behave unexpectedly in others, and to show the standard ways to filter on their results.
The logical order of a query
You write SELECT first, but the database does not run it first. Conceptually it processes the clauses in this order:
FROMandJOINbuild the working set of rows.WHEREremoves rows.GROUP BYcollapses rows into groups.HAVINGremoves groups.- Window functions are calculated over the rows that remain.
SELECTproduces the output columns, including window results.DISTINCTremoves duplicate output rows.ORDER BYsorts the result.LIMITorFETCHtrims it.
Optimizers may physically reorder work, but they must return the result this order describes.
Two consequences follow from the position of step 5:
- A window function can only see rows that survived
WHERE,GROUP BYandHAVING. WHERE,GROUP BYandHAVINGrun before window results exist, so they cannot use them.
Sample data
The examples use this table. It runs as written in PostgreSQL, and in SQLite 3.25+ if you replace DATE with TEXT.
CREATE TABLE sales (
id INTEGER PRIMARY KEY,
region VARCHAR(20),
salesperson VARCHAR(20),
amount INTEGER,
sale_date DATE
);
INSERT INTO sales (id, region, salesperson, amount, sale_date) VALUES
(1, 'East', 'Ana', 300, '2026-01-05'),
(2, 'East', 'Ben', 300, '2026-01-12'),
(3, 'East', 'Cara', 150, '2026-02-03'),
(4, 'East', 'Dev', 50, '2026-02-20'),
(5, 'West', 'Eli', 400, '2026-01-09'),
(6, 'West', 'Fay', 100, '2026-01-30'),
(7, 'West', 'Gus', 80, '2026-02-14');Why WHERE rejects window functions
The most common beginner error is filtering on a window result directly:
-- Fails: window functions are not allowed in WHERE
SELECT region, salesperson, amount
FROM sales
WHERE ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) <= 3;PostgreSQL reports window functions are not allowed in WHERE. SQL Server and MySQL give similar messages. The reason is the order above: when WHERE runs, the rows have not been ranked yet. The same rule applies to GROUP BY and HAVING.
Window functions are legal in only two places: the SELECT list and the ORDER BY clause.
You also cannot reuse a window result by its alias in the same SELECT, because aliases are assigned when the select list is produced:
-- Fails: alias rn does not exist yet in WHERE
SELECT region, amount,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS rn
FROM sales
WHERE rn <= 3;The standard fix: compute first, filter second
Put the window function in an inner query, then filter in an outer query. The inner query's output is an ordinary set of rows with an ordinary rn column. A CTE and a derived table are equivalent here.
WITH ranked AS (
SELECT
region,
salesperson,
amount,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS rn
FROM sales
)
SELECT region, salesperson, amount
FROM ranked
WHERE rn <= 3;The subquery form gives the same result:
SELECT region, salesperson, amount
FROM (
SELECT
region,
salesperson,
amount,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS rn
FROM sales
) AS ranked
WHERE rn <= 3;Use a CTE when the query has several stages or the intermediate result is referenced more than once. Use a subquery for a short one-off filter. Neither changes what the optimizer can do in most engines.
Choosing the ranking function for the filter
The function you filter on decides how ties behave. In the sample data, Ana and Ben both sold 300 in the East.
ROW_NUMBER() <= 2returns exactly two East rows, and which tied row is dropped is arbitrary unless theORDER BYhas a tiebreaker such asid.RANK() <= 2returns every row ranked 1 or 2. With Ana and Ben tied at rank 1, Cara is rank 3, so the result is Ana and Ben.DENSE_RANK() <= 2returns every row whose amount is among the two highest distinct values, so Ana, Ben and Cara.
Pick ROW_NUMBER when you need exactly N rows per group, and add a tiebreaker for deterministic output. Pick RANK or DENSE_RANK when ties should be kept together.
Filtering on LAG and LEAD results
The same pattern works for any window function. To find months where revenue fell, compute the change inside, then filter outside:
WITH monthly AS (
SELECT
EXTRACT(MONTH FROM sale_date) AS sale_month,
SUM(amount) AS revenue
FROM sales
GROUP BY EXTRACT(MONTH FROM sale_date)
),
changes AS (
SELECT
sale_month,
revenue,
revenue - LAG(revenue) OVER (ORDER BY sale_month) AS change_from_prev
FROM monthly
)
SELECT sale_month, revenue, change_from_prev
FROM changes
WHERE change_from_prev < 0;This query uses both the GROUP BY and window steps in sequence. The first CTE aggregates by month. The second applies LAG to the aggregated rows. The first month has NULL for change_from_prev, and NULL < 0 is not true, so that row is excluded.
WHERE runs before the window
Because WHERE runs first, any row it removes is invisible to the window function. This is often what you want, but it can silently change the numbers. Compare these two queries, which both show each East and West sale with its region total:
-- Region total counts only sales of 100 or more
SELECT id, region, amount,
SUM(amount) OVER (PARTITION BY region) AS region_total
FROM sales
WHERE amount >= 100;For the East this gives a total of 750. For the West it gives 500, because Gus's sale of 80 was removed before the sum.
If you want each large sale shown beside the full regional total, calculate the window first and filter afterwards:
WITH with_totals AS (
SELECT id, region, amount,
SUM(amount) OVER (PARTITION BY region) AS region_total
FROM sales
)
SELECT id, region, amount, region_total
FROM with_totals
WHERE amount >= 100;Now the West total is 580 on every West row. The same query text with the filter in a different place gives a different answer, so decide which one the question needs.
Windows over grouped results
Step 5 follows GROUP BY, so a window function can operate on group results. The window's argument can then be an aggregate. This is why SUM(SUM(amount)) OVER () is valid:
SELECT
region,
SUM(amount) AS region_total,
SUM(SUM(amount)) OVER () AS grand_total,
100.0 * SUM(amount) / SUM(SUM(amount)) OVER () AS pct_of_total
FROM sales
GROUP BY region;The inner SUM runs during grouping and produces one value per region. The outer SUM ... OVER () then adds those per-region values across all output rows. The empty OVER () means one window containing every row.
Inside a grouped query, a window function may only use grouped columns and aggregates. Using a raw column such as amount outside an aggregate fails with the same error as any other ungrouped column.
Window functions in ORDER BY
ORDER BY runs after the window step, so it may call a window function directly or use the alias of a window column in the select list:
SELECT salesperson, amount,
RANK() OVER (ORDER BY amount DESC) AS rnk
FROM sales
ORDER BY rnk, salesperson;This ORDER BY belongs to the query as a whole. It has no effect on how the window ordered its rows, which was set by the ORDER BY inside OVER.
QUALIFY: filtering without a wrapper
Some engines add a QUALIFY clause that filters after window functions, the way HAVING filters after GROUP BY. Snowflake, BigQuery, Databricks, DuckDB and Teradata support it.
SELECT region, salesperson, amount
FROM sales
QUALIFY ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) <= 3;PostgreSQL, MySQL, SQL Server, SQLite and Oracle do not have QUALIFY, and it is not part of standard SQL. Queries using it will not port. The CTE pattern works everywhere, so use it unless your team is committed to one of the engines above.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Window function in `WHERE` | "window functions are not allowed in WHERE" | Move it to a CTE or subquery and filter outside |
| Using a window alias in the same `WHERE` | "column does not exist" | Filter in the outer query |
| Window function in `GROUP BY` or `HAVING` | Same error | Aggregate in one step, window in the next |
| Filtering rows in the same query as the window | Totals or ranks smaller than expected | Compute the window first, then filter outside |
| `ROW_NUMBER` filter without a tiebreaker | Different rows on different runs | Add a unique column such as `id` to the window `ORDER BY` |
Exercise
Write a query that returns each region's single largest sale, keeping all rows that tie for the largest, and also shows that region's total sales. Use only the sample sales table and no QUALIFY clause.
Show answer
WITH ranked AS ( SELECT region, salesperson, amount, RANK() OVER (PARTITION BY region ORDER BY amount DESC) AS rnk, SUM(amount) OVER (PARTITION BY region) AS regiontotal FROM sales ) SELECT region, salesperson, amount, regiontotal FROM ranked WHERE rnk = 1; The window functions are computed in the CTE and filtered in the outer query, because WHERE cannot see them. RANK keeps ties, so Ana and Ben both appear for the East with a regiontotal of 800. The West returns Eli with 580. Because regiontotal is calculated before the filter, it includes every sale.
Exercise
A colleague writes SELECT region, amount, SUM(amount) OVER (PARTITION BY region) AS region_total FROM sales WHERE salesperson <> 'Eli'. They expect the West total to be 580 but get 180. Why, and how do you get 580 while still hiding Eli's row?
Show answer
WHERE runs before window functions, so Eli's sale of 400 is removed before SUM is calculated, leaving 100 + 80 = 180. Compute the total in a CTE without the filter, then filter in the outer query: WITH t AS (SELECT region, salesperson, amount, SUM(amount) OVER (PARTITION BY region) AS regiontotal FROM sales) SELECT region, amount, regiontotal FROM t WHERE salesperson <> 'Eli'.