Practice — Case Study: The SQL Interview Gauntlet (5 questions)
Advanced
Open
Free
Median Salary Per Department, Two Ways Permalink →
You're given this table:
salaries
employee_id | department_id | salary
------------+----------------+-------
1 | 10 | 60000
2 | 10 | 72000
3 | 10 | 85000
4 | 10 | 90000
5 | 20 | 55000
6 | 20 | 61000
7 | 20 | 70000
Compute the median salary per department. Department 10 has an even number of rows (4), department 20 has an odd number (3) — your query needs to handle both correctly, since the median definition differs (average the two middle values vs. take the single middle value).
- Write a solution using
PERCENTILE_CONT, and explain what the0.5andWITHIN GROUP (ORDER BY ...)actually mean mechanically. - Now write a solution that computes the same result without any
built-in median/percentile function, using only
ROW_NUMBER(),COUNT(), and standard aggregation — the way you'd need to on an engine that doesn't supportPERCENTILE_CONT. - Which would you actually use in production, and why?
Share this question
Advanced
Open
Pro