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
idfirst_namelast_nameemaildepartment_idsalaryhire_datemanager_idtitle
1AliceChen[email protected]12500002015-01-15NULLCEO
2RobertMartinez[email protected]21800002016-03-20NULLCEO
3SarahJohnson[email protected]11500002017-06-101VP Engineering
departments 5 rows
  • id integer PK
  • name text
  • location text
idnamelocation
1EngineeringSan Francisco
2SalesNew York
3MarketingLos Angeles

Keep going