SQL interview question: Median Without a MEDIAN Function
Department Salary Median (No MEDIAN Function)
Google interviews often test whether you can implement statistical functions manually when they're not built-in.
Calculate the median salary for each department using ROW_NUMBER() - no MEDIAN() or PERCENTILE() allowed.
Return department_name and median_salary. For even counts, average the two middle values. Order by department_name.
Inspired by Google's algorithmic SQL questions
Tables
employees 37 rows
- id integer PK
- first_name text
- last_name text
- email text
- department_id integer → departments
- salary integer
- hire_date text
- manager_id integer → employees
- title text
| id | first_name | last_name | department_id | salary | hire_date | manager_id | title | |
|---|---|---|---|---|---|---|---|---|
| 1 | Alice | Chen | [email protected] | 1 | 250000 | 2015-01-15 | NULL | CEO |
| 2 | Robert | Martinez | [email protected] | 2 | 180000 | 2016-03-20 | NULL | CEO |
| 3 | Sarah | Johnson | [email protected] | 1 | 150000 | 2017-06-10 | 1 | VP Engineering |
departments 5 rows
- id integer PK
- name text
- location text
| id | name | location |
|---|---|---|
| 1 | Engineering | San Francisco |
| 2 | Sales | New York |
| 3 | Marketing | Los Angeles |