InterviewPrepKit

Home / SQL / Advanced Patterns

Median Salary Per Department

medium
Solving tips
  • SQL has no MEDIAN aggregate; use the ordered-set function `PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY col)`.
  • PERCENTILE_CONT interpolates between the two middle values for even counts, so a group of {120,140} yields 130, not one of the endpoints.
  • The ORDER BY lives inside WITHIN GROUP, while GROUP BY on the outside defines the buckets you want a median for.

Given salaries tagged by department, compute the median salary of each department.

Schema

CREATE TABLE salaries (
  department  TEXT,
  salary      INTEGER
);

Sample data:

departmentsalary
Engineering100
Engineering120
Engineering140
Engineering160
Sales50
Sales70
Sales90

Task

Return one row per department with columns department and median_salary. Use the continuous (interpolated) median: for an even number of rows it is the average of the two middle values. Order by department ascending.

Expected output

departmentmedian_salary
Engineering130
Sales70
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.