Querydrill

Level 5: Interview classics Exercise 107 of 161 Hard Ranking and top N per group

Median salary

An SQL exercise from Querydrill. Solve it with a SQL editor in your browser, checked on the rows it returns and again on changed data, and it is checked the moment you submit.

Try it yourself

Return the median salary of all employees as a single value: the middle salary when they are sorted, or the average of the two middle salaries when the number of employees is even.

employees (11 rows)

idnamedept_idsalaryhire_datemanager_id
1Ava21300002019-03-15NULL
2Ben21050002020-07-011
3Cleo1820002021-01-107
4Dan1760002022-05-237
5Eve3540002022-09-1211
6Finn2980002021-11-301
7Gia1990002018-06-04NULL
8Hugo3610002020-02-18NULL
9Iris4880002019-10-07NULL
10Jack4720002023-04-179
11KaiNULL500002024-01-088

Free, no account needed. PostgreSQL runs in your browser and your answer is checked again on changed data.

What this exercise teaches

This is asked to see whether you can build a median by hand. With integer division, (n + 1) / 2 and (n + 2) / 2 are the same row for an odd count and the two middle rows for an even count. PostgreSQL also has PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary), which is accepted here too.

A hint if you get stuck

Number the salaries with ROW_NUMBER() OVER (ORDER BY salary) and put COUNT(*) OVER () next to it as n. The middle rows are (n + 1) / 2 and (n + 2) / 2 with integer division; average them.

Background you need

Common mistakes on this exercise

  • The mean, not the median.
  • Works for an odd count only: on an even count it returns the lower middle salary.

Each of these returns a result that looks plausible. The checker catches them because it runs your query on changed data as well.

Keep going on the practice page

Your first 8 exercises on Querydrill are free, with no account. The practice page has the full editor, timed mode and all the exercises in order. A free account shows 3 reference solutions a day; Pro unlocks every exercise, every solution, timed mode and the certificate.

Open this exercise

More practice on the same topic

More exercises in Interview classics