HardPro challengeSQL
Median Salary Without MEDIAN()
SQLDatabases
SQLite has no built-in MEDIAN() function. Write a SQL query that computes
the median salary from the employees table using window functions.
The median is the middle value when rows are sorted:
- Odd count → the single middle row.
- Even count → the average of the two middle rows.
Table: employees
| id | name | salary |
|---|---|---|
| 1 | Alice | 40000 |
| 2 | Bob | 55000 |
| 3 | Carol | 70000 |
| 4 | Dave | 85000 |
| 5 | Eve | 95000 |
Sorted: 40000 · 55000 · 70000 · 85000 · 95000 → median = 70000
Expected output (column: median)
70000.0Key insight — assign each row a rank with
ROW_NUMBER() OVER (ORDER BY salary)and compute the total row count with
COUNT(*) OVER ().For a table with
Nrows, the median row(s) are at positions
(N+1)/2and(N+2)/2(integer division). TakingAVGof thoserow(s) handles both odd and even N.
Sample tests
Test #1Odd count (5) — middle row is rank 3 = 70000
Input: "CREATE TABLE employees (id INTEGER, name TEXT, salary INTEGER);\nINSERT INTO employees VALUES\n (1, 'Alice', 40000),\n (2, 'Bob', 55000),\n (3, 'Carol', 70000),\n (4, 'Dave', 85000),\n (5, 'Eve', 95000);"
Output: "70000.0"