Explore Library
Code QuizAdvanced

Filtering on a Window Function Result

Spot why filtering directly on a window function in WHERE fails and how a CTE fixes it.

Codesql
SELECT
  employee_id,
  department_id,
  salary,
  RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS salary_rank
FROM employees
WHERE RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) <= 3;

What is the bug in this query, which is meant to return the top 3 earners per department?