The average is easy in SQL, but it can mislead: one very large order pulls it far above what a typical customer spends. The median, the middle value, is often a fairer “typical” number. SQL also lets you split rows into equal bands, such as top, middle and bottom thirds, and say what fraction of rows each value beats. This lesson covers NTILE, PERCENT_RANK, CUME_DIST and a median that works in any database.
In this lesson you will learn
- Splitting rows into bands with
NTILE - Relative position with
PERCENT_RANKandCUME_DIST - Calculating a median with
ROW_NUMBERandCOUNT - Median for each group
- When to report the median instead of the mean
You should know window functions and aggregate functions.
Bands and Relative Position
-- Split employees into salary bands, and see where each one stands
SELECT name, salary,
NTILE(3) OVER (ORDER BY salary) AS band,
ROUND(PERCENT_RANK() OVER (ORDER BY salary), 2) AS pct_rank,
ROUND(CUME_DIST() OVER (ORDER BY salary), 2) AS cume_dist
FROM employees
ORDER BY salary;
Output
+---------+--------+------+----------+-----------+
| name | salary | band | pct_rank | cume_dist |
+---------+--------+------+----------+-----------+
| Sumi | 25000 | 1 | 0.0 | 0.14 |
| Anik | 70000 | 1 | 0.17 | 0.29 |
| Rubel | 90000 | 1 | 0.33 | 0.43 |
| Mou | 95000 | 2 | 0.5 | 0.57 |
| Lipi | 170000 | 2 | 0.67 | 0.71 |
| Faisal | 180000 | 3 | 0.83 | 0.86 |
| Shahana | 250000 | 3 | 1.0 | 1.0 |
+---------+--------+------+----------+-----------+
(7 rows)
NTILE(3)splits the sorted rows into 3 bands as evenly as possible. Seven rows do not divide by 3, so the first band gets the extra row: 3, 2 and 2.PERCENT_RANKis (rank − 1) / (rows − 1). The lowest salary gets 0, the highest gets 1, and Mou, in the middle, gets 0.5.CUME_DISTis the share of rows with a value less than or equal to this one. Mou’s 0.57 means 4 out of 7 employees earn 95,000 or less.- Use
NTILE(4)for quartiles,NTILE(10)for deciles andNTILE(100)for percentile groups.
Calculating the Median
SQLite has no built-in MEDIAN function, and neither do MySQL and SQL Server. This method works everywhere: number the sorted rows, then pick the middle one, or the two middle ones when the count is even, and average them.
-- Median order amount (ignoring the order with no amount)
WITH ranked AS (
SELECT amount,
ROW_NUMBER() OVER (ORDER BY amount) AS rn,
COUNT(*) OVER () AS n
FROM orders
WHERE amount IS NOT NULL
)
SELECT AVG(amount) AS median
FROM ranked
WHERE rn IN ((n + 1) / 2, (n + 2) / 2);
-- Compare with the mean: one big order pulls the mean up
SELECT ROUND(AVG(amount), 1) AS mean FROM orders;
-- Median marks per course
WITH ranked AS (
SELECT course_id, marks,
ROW_NUMBER() OVER (PARTITION BY course_id ORDER BY marks) AS rn,
COUNT(*) OVER (PARTITION BY course_id) AS n
FROM enrollments
)
SELECT course_id, AVG(marks) AS median_marks, MAX(n) AS students
FROM ranked
WHERE rn IN ((n + 1) / 2, (n + 2) / 2)
GROUP BY course_id;
Output
+--------+
| median |
+--------+
| 800.0 |
+--------+
(1 row)
+--------+
| mean |
+--------+
| 1028.6 |
+--------+
(1 row)
+-----------+--------------+----------+
| course_id | median_marks | students |
+-----------+--------------+----------+
| 101 | 91.5 | 2 |
| 102 | 90.0 | 3 |
| 201 | 72.5 | 2 |
| 301 | 78.5 | 2 |
+-----------+--------------+----------+
(4 rows)
COUNT(*) OVER ()puts the total row count, n, on every row.- With integer division,
(n + 1) / 2and(n + 2) / 2are the same row when n is odd, and the two middle rows when n is even. Averaging them handles both cases. - The 7 order amounts have a median of 800, but a mean of 1,028.6. The 2,300 order pulls the mean up; the median ignores how extreme it is.
- Adding
PARTITION BY course_idgives a median per course. Course 102 has three students (92, 90, 76), so its median is the middle mark, 90. - The order with no amount is filtered out first.
AVGignores NULLs too, so the mean also uses 7 orders.
Built-in Options in Other Databases
| Database | Median |
|---|---|
| PostgreSQL | PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY amount) |
| SQL Server | PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY amount) OVER () |
| Oracle | MEDIAN(amount) or PERCENTILE_CONT |
| SQLite, MySQL | The ROW_NUMBER method from this lesson |
PERCENTILE_CONT works for any percentile: 0.9 gives the value below which 90% of rows fall.
Common Mistakes
- Taking the middle row of an unsorted table. The median needs
ORDER BYinside the window. - Counting NULLs in n. Filter out NULLs before numbering, or the middle row shifts.
- Treating NTILE bands as equal value ranges. NTILE makes groups with equal numbers of rows, not equal salary ranges.
- Using RANK for the median. Ties give equal ranks, so the middle position may be skipped.
ROW_NUMBERgives every row a unique number.
Practice Exercises
Exercise 1. Find the median CGPA of all students who have one.
Show answer
WITH r AS (
SELECT cgpa, ROW_NUMBER() OVER (ORDER BY cgpa) AS rn, COUNT(*) OVER () AS n
FROM students WHERE cgpa IS NOT NULL
)
SELECT AVG(cgpa) AS median FROM r WHERE rn IN ((n + 1) / 2, (n + 2) / 2);
Seven students have a CGPA, so the median is the 4th value: 3.55.
Exercise 2. Label each employee “top half” or “bottom half” by salary.
Show answer
SELECT name, salary,
CASE NTILE(2) OVER (ORDER BY salary DESC) WHEN 1 THEN 'top half' ELSE 'bottom half' END AS half
FROM employees;
Frequently Asked Questions
What is the difference between PERCENT_RANK and CUME_DIST?
PERCENT_RANK measures the share of other rows that rank strictly below this one, from 0 to 1. CUME_DIST measures the share of all rows at or below this value, so it is never 0. For large tables they give similar numbers.
Is the median always better than the mean?
No. The mean uses every value and is right for totals, such as revenue per day. The median is better for a “typical” value when the data is skewed, such as incomes or house prices.
Summary
NTILE(n)splits sorted rows into n bands of nearly equal size.PERCENT_RANKandCUME_DISTshow a row’s relative position.- Median: number the rows, average the one or two middle rows.
- Prefer the median for skewed data such as order amounts.
