Bird
0
0

Identify the error in this query that attempts to select the top 1 salary per department:

medium📝 Debug Q6 of 15
SQL - Advanced Query Patterns
Identify the error in this query that attempts to select the top 1 salary per department:

SELECT department, employee, salary, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM employees WHERE rn = 1;
AMissing GROUP BY clause
BROW_NUMBER() cannot be used with PARTITION BY
CCannot use alias rn in WHERE clause directly
DORDER BY salary DESC is invalid syntax
Step-by-Step Solution
Solution:
  1. Step 1: Understand alias scope in SQL

    Aliases like rn defined in SELECT cannot be used in WHERE clause directly.
  2. Step 2: Correct approach

    Use a subquery or CTE to assign rn, then filter in outer query.
  3. Final Answer:

    Cannot use alias rn in WHERE clause directly -> Option C
  4. Quick Check:

    Alias in SELECT not usable in WHERE [OK]
Quick Trick: Filter on ROW_NUMBER() alias in outer query, not WHERE [OK]
Common Mistakes:
  • Trying to filter alias in WHERE instead of outer query
  • Adding unnecessary GROUP BY
  • Misunderstanding ROW_NUMBER() usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes