Sub topic 8
Where Window Functions Run and How to Filter on Them
Assume you know SELECT, WHERE, ORDER BY, GROUP BY, aggregate functions, subqueries, and common table expressions (CTEs). A window function calculates a value from related rows while keeping the original rows. Examples include ROW_NUMBER(), SUM() OVER (...), and LAG().
Window functions run after filtering
SQL processes a query in a logical order. The database first finds rows, filters them, groups them, and then calculates window functions over the remaining rows.
This order explains an important rule: a window function cannot normally appear in WHERE. At the time WHERE runs, the window value does not exist yet.
For example, this is invalid:
SELECT
region,
salesperson,
amount,
ROW_NUMBER() OVER (
PARTITION BY region
ORDER BY amount DESC
) AS rn
FROM sales
WHERE rn <= 3;The alias rn is created by the SELECT list, after WHERE has already been evaluated. Even repeating the window expression in WHERE does not solve the problem in most SQL databases.
Compute first, filter second
Use a CTE or subquery to create the window value in one query level. Then filter it in an outer query.
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
ORDER BY region, rn;The inner query assigns a number to every sale within its region. The outer query keeps only rows numbered 1 through 3. This is the common top-N per group pattern.
The WHERE clause inside the CTE still matters. It limits the rows before ranking:
WITH ranked AS (
SELECT
region,
salesperson,
amount,
ROW_NUMBER() OVER (
PARTITION BY region
ORDER BY amount DESC
) AS rn
FROM sales
WHERE sale_date >= DATE '2026-01-01'
)
SELECT region, salesperson, amount
FROM ranked
WHERE rn <= 3;This returns the top three sales per region during 2026, not the top three from all time.
Filtering and ties
ROW_NUMBER() always produces unique numbers. If two sales have the same amount, one still receives a lower number. Add a tie-breaker such as id when the choice must be repeatable.
Use RANK() when tied rows should share a position and the next position should be skipped. Use DENSE_RANK() when tied rows should share a position without a gap.
WITH ranked AS (
SELECT
region,
salesperson,
amount,
RANK() OVER (
PARTITION BY region
ORDER BY amount DESC
) AS rnk
FROM sales
)
SELECT region, salesperson, amount
FROM ranked
WHERE rnk <= 3;This can return more than three rows for a region because every row tied at rank 3 is included.
Exercise
You need exactly two rows per department, even when salaries are tied. Which ranking function should you use?
Show answer
Use ROWNUMBER(), with a deterministic tie-breaker such as employeeid in the window ORDER BY.