Interview Questions/SQL/Median Salary Per Department

Median Salary Per Department

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a table of employee salaries. Each row has an employee name, a department, and a salary. Write a SQL query to find the median salary for each department. For departments with an even number of employees, return the average of the two middle values. Return the result ordered by department. Table: Salaries

Column NameTypeDescription
idINTPrimary key
employeeVARCHAREmployee name
departmentVARCHARDepartment name
salaryINTAnnual salary

Database Schema (Inferred)

Salaries

Column NameExample Value
id1
employeeAlice
departmentEng
salary90000

Example

Salaries

idemployeedepartmentsalary
1AliceEng90000
2BobEng80000
3CarolEng70000
4DaveEng60000
5EveHR50000
6FrankHR55000
7GraceHR45000

Output

departmentmedian_salary
Eng75000
HR50000

Explanation:

Eng has 4 employees (even). Sorted: 60000, 70000, 80000, 90000. Median = (70000+80000)/2 = 75000. HR has 3 employees (odd). Sorted: 45000, 50000, 55000. Median = 50000.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Salaries

idemployeedepartmentsalary
1AliceEng90000
2BobEng80000
3CarolEng70000
4DaveEng60000
5EveHR50000
6FrankHR55000
7GraceHR45000

Output

departmentmedian_salary
Eng75000
HR50000