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:
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