Interview Puzzles · Problem 96 of 118

Median Product Price

HardInterview PuzzlesShop data

SQLite has no MEDIAN function. Return one row with median_price: the median of products.price.

If the number of products is even, the median is the average of the two middle prices; if it is odd, it is the middle price. Write the query so that it is correct for both cases.

Hint 1

Number the prices in order with ROW_NUMBER() and count them with COUNT(*) OVER ().

Hint 2

The middle rows are the ones where n is (total + 1) / 2 and (total + 2) / 2 (integer division). For an odd total these are the same row; for an even total they are the two middle rows.

Reference solution

WITH numbered AS (
  SELECT price,
         ROW_NUMBER() OVER (ORDER BY price) AS n,
         COUNT(*) OVER () AS total
  FROM products
)
SELECT AVG(price) AS median_price
FROM numbered
WHERE n IN ((total + 1) / 2, (total + 2) / 2);

The median is the value in the middle of the sorted list. (total + 1) / 2 and (total + 2) / 2 pick the middle position for an odd total (both equal) and the two middle positions for an even total, and AVG of one or two numbers is exactly the median. Ties do not matter: ROW_NUMBER still gives every row a distinct position. Know this one by heart; "median" and "percentile" questions come up constantly, and databases that have PERCENTILE_CONT hide the same idea.