Chapter 8 · Lesson 6 of 8
Why Window Functions Cannot Go Directly in WHERE
Learn why window functions cannot appear in WHERE and how a subquery or CTE lets you filter to the top-ranked row in each group.
A common beginner question is: “If window functions run late, can I filter on them in WHERE?”
Usually, no. WHERE happens earlier than window functions in SQL's logical order.
So a query like this is conceptually backwards:
SELECT salesperson, amount,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS region_rank
FROM sales
WHERE region_rank = 1At the moment WHERE runs, region_rank does not exist yet.
The usual fix is to compute the window function in a subquery or CTE first, then filter the outer query:
WITH ranked_sales AS (
SELECT region, salesperson, amount,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS region_rank
FROM sales
)
SELECT region, salesperson, amount
FROM ranked_sales
WHERE region_rank = 1That works because the outer query's WHERE sees region_rank as a normal column from the inner query result.
DuckDB also supports QUALIFY, which filters after window functions. A QUALIFY region_rank = 1 clause can be a concise alternative to the subquery pattern.
Sample data
This lesson loads the sales table (8 rows) into DuckDB in your browser with one click, so you can run every example without uploading anything.
Setup SQL for sales
CREATE OR REPLACE TABLE sales (
id INTEGER,
salesperson VARCHAR,
region VARCHAR,
amount DECIMAL(10,2),
quantity INTEGER,
sale_date DATE
);
INSERT INTO sales VALUES
(1, 'Alice', 'West', 1200, 3, '2024-01-05'),
(2, 'Bob', 'East', 850, 2, '2024-01-08'),
(3, 'Alice', 'West', 640, 1, '2024-01-11'),
(4, 'Diana', 'South', 430, 5, '2024-01-12'),
(5, 'Eve', 'West', 1500, 4, '2024-02-01'),
(6, 'Frank', 'East', 920, 2, '2024-02-03'),
(7, 'Grace', 'North', 760, 2, '2024-02-07'),
(8, 'Bob', 'East', 1100, 3, '2024-02-10');Practice challenge
Return the top sale in each region. Show region, salesperson, amount, and region_rank, ordered by region. Use a subquery or CTE so you can filter to region_rank = 1.
Hint: First compute ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) in an inner query, then filter the outer query to region_rank = 1.
Run your query in the editor and the lesson checks the result automatically.
Lessons in Execution Order
Understand the logical order in which SQL evaluates FROM, WHERE, GROUP BY, HAVING, window functions, SELECT, ORDER BY, and LIMIT.
Related guides
SQL Execution Order Explained: Why WHERE, GROUP BY, HAVING, SELECT, and LIMIT Behave Differently
SQL is written in one order but understood in another; learning the logical order explains many beginner surprises.
SQL Subqueries vs CTEs: When to Use WITH, IN, EXISTS, and Correlated Subqueries
Subqueries nest one question inside another; CTEs give each step a name. Learn which form to use, and the NULL trap that makes NOT IN return nothing.