Part 07 / Topic 8 of 8
Where windows are evaluated
Extend Part 2's evaluation order with one entry: windows run after WHERE, GROUP BY and HAVING — on the surviving rows — and before DISTINCT/ORDER BY/LIMIT:
FROM → WHERE → GROUP BY → HAVING → [window functions] → SELECT → ORDER BY → LIMIT
Two consequences, both load-bearing. First, you may not filter on a window result in WHERE — it doesn't exist yet:
SELECT name, price,
RANK() OVER (ORDER BY price DESC) AS rnk
FROM products
WHERE RANK() OVER (ORDER BY price DESC) <= 3;
ERROR: window functions are not allowed in WHERE
LINE 4: WHERE RANK() OVER (ORDER BY price DESC) <= 3;
^
The fix is an outer query — compute the window in a CTE or subquery, filter one level up:
WITH ranked AS (
SELECT name, price,
RANK() OVER (ORDER BY price DESC) AS rnk
FROM products
)
SELECT name, price, rnk FROM ranked WHERE rnk <= 3;
name | price | rnk
---------------+---------+-----
Laptop Pro 14 | 1200.00 | 1
Laptop Air 13 | 950.00 | 2
Phone X | 799.00 | 3
(3 rows)
Second, windows see rows after WHERE — so filters change the rankings. Rank products in stock and the out-of-stock Coffee Maker isn't just hidden, it was never ranked. Decide whether your WHERE belongs before the window (rank the survivors) or after it (rank everyone, then hide) — they are different reports.
🧪 Quick quiz — answer from memory, then check.
- Can WHERE test a window function's result?
- Does a WHERE clause affect what a window function sees?
Show the answers
- No — windows are evaluated after WHERE. Wrap the query and filter outside.
- Yes — windows run on the rows that survived WHERE, so filters change ranks and totals.
Exercise 8: One winner per category
What to do: The single most expensive product per category — the window-function spelling of Part 2's DISTINCT ON.
Sample output:
category_id | name | price
-------------+--------------------+---------
1 | USB-C Cable | 15.00
2 | Postgres Deep Dive | 55.00
3 | Desk Lamp | 45.00
4 | Laptop Pro 14 | 1200.00
5 | Phone X | 799.00
6 | Coffee Maker | 120.00
(6 rows)
💡 Hint: ROW_NUMBER() OVER (PARTITION BY ... ORDER BY price DESC), keep rn = 1.
Show the solution to Exercise 8
-- Exercise 8: One winner per category
-- ROW_NUMBER (never ties) = exactly one row per category — the same answer
-- Part 2's DISTINCT ON gave, now in the portable spelling.
WITH ranked AS (
SELECT category_id, name, price,
ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY price DESC) AS rn
FROM products
)
SELECT category_id, name, price
FROM ranked
WHERE rn = 1
ORDER BY category_id;