Can window functions be used in a WHERE clause? If not, why, and what's the alternative?
Quick Overview
Asks whether a SQL window function such as ROW_NUMBER can appear in a WHERE clause, why or why not, and how to filter on its result instead. Tests logical query processing order, the CTE or subquery rewrite, and how ties and filter placement change the rows returned.
Can window functions be used in a WHERE clause? If not, why, and what's the alternative?
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Can window functions be used in a `WHERE` clause? If not, why, and what's the alternative?
For example, you want the highest-paid employee in each department, and you compute `ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC)` to find them.
```hint Think about evaluation order
List the clauses of a SELECT statement in the order the engine logically evaluates them, and find the step where window functions are computed.
```
### What a Strong Answer Covers
- A direct answer, with the reason grounded in logical query processing order
- Where window functions are evaluated relative to `WHERE`, `GROUP BY` and `HAVING`
- A working rewrite that filters on the window result
- How tie handling and the placement of other filters change the result
### Follow-up Questions
- Some engines offer a `QUALIFY` clause. What does it do, and does it match the CTE rewrite?
- Can a window function appear in `HAVING` or in `ORDER BY`?
- You also need to keep only active employees. Does that filter go inside the CTE or in the outer query?
- How would you return every employee tied for the top salary in each department?
Overview: Asks whether a SQL window function such as ROW_NUMBER can appear in a WHERE clause, why or why not, and how to filter on its result instead. Tests logical query processing order, the CTE or subquery rewrite, and how ties and filter placement change the rows returned.
Can window functions be used in a WHERE clause? If not, why, and what's the alternative?
For example, you want the highest-paid employee in each department, and you compute ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) to find them.
What a Strong Answer Covers Guidance
A direct answer, with the reason grounded in logical query processing order
Where window functions are evaluated relative to
WHERE
,
GROUP BY
and
HAVING
A working rewrite that filters on the window result
How tie handling and the placement of other filters change the result
Follow-up Questions Guidance
Some engines offer a
QUALIFY
clause. What does it do, and does it match the CTE rewrite?
Can a window function appear in
HAVING
or in
ORDER BY
?
You also need to keep only active employees. Does that filter go inside the CTE or in the outer query?
How would you return every employee tied for the top salary in each department?