Partition by department + order by salary DESC = correct row numbers [OK]
Hint: Partition groups restart numbering; order controls row number sequence [OK]
Common Mistakes:
Ignoring PARTITION BY and numbering globally
Ordering ascending instead of descending
Assigning same row number to multiple rows
4. Identify the error in this query:
SELECT id, ROW_NUMBER() PARTITION BY department ORDER BY salary FROM Employees;
medium
A. Missing OVER() keyword before PARTITION BY clause.
B. ORDER BY cannot be used inside ROW_NUMBER().
C. PARTITION BY should be after ORDER BY.
D. ROW_NUMBER() cannot be used with SELECT.
Solution
Step 1: Check ROW_NUMBER() syntax
ROW_NUMBER() requires OVER() before PARTITION BY and ORDER BY clauses.
Step 2: Identify missing OVER()
The query misses OVER(), causing syntax error.
Final Answer:
Missing OVER() keyword before PARTITION BY clause. -> Option A
Quick Check:
ROW_NUMBER() must have OVER() [OK]
Hint: Always use OVER() with ROW_NUMBER() [OK]
Common Mistakes:
Omitting OVER() keyword
Placing PARTITION BY outside OVER()
Misordering clauses inside OVER()
5. You want to select the top 2 highest paid employees per department from the Employees table. Which query correctly uses ROW_NUMBER() to achieve this?
hard
A. SELECT id, department, salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS rn FROM Employees WHERE rn <= 2;
B. SELECT *, ROW_NUMBER() FROM Employees WHERE rn <= 2 PARTITION BY department ORDER BY salary DESC;
C. SELECT id, department, salary FROM Employees ORDER BY salary DESC LIMIT 2 PARTITION BY department;
D. SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM Employees) AS t WHERE rn <= 2;
Solution
Step 1: Use ROW_NUMBER() with PARTITION BY department and ORDER BY salary DESC
This assigns row numbers restarting at 1 for each department, ordered by salary descending.
Step 2: Filter rows where row number is 2 or less
Wrap the window function query as a subquery and filter with WHERE rn <= 2 to get top 2 per department.
Final Answer:
SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM Employees) AS t WHERE rn <= 2; -> Option D
Quick Check:
Use subquery with ROW_NUMBER() and filter rn <= 2 [OK]
Hint: Use subquery with ROW_NUMBER() and filter rn <= 2 [OK]
Common Mistakes:
Filtering rn in outer query without subquery
Using LIMIT with PARTITION BY incorrectly
Omitting PARTITION BY causing global numbering
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.