Sub topic 14
Buckets and percentiles: NTILE, PERCENT_RANK, CUME_DIST
This chapter assumes you can write an OVER (PARTITION BY ... ORDER BY ...) clause and use ROW_NUMBER, RANK and DENSE_RANK. It also assumes you can filter window results through a CTE. The functions here answer a different question from ranking: not "what place is this row in?" but "what share of the rows is this row ahead of?"
What the three functions do
NTILE(n)splits the ordered rows of a partition intonbuckets of nearly equal size and returns the bucket number, from 1 ton.PERCENT_RANK()returns the relative rank of a row as a value from 0 to 1. The formula is(rank - 1) / (rows_in_partition - 1).CUME_DIST()returns the cumulative distribution, from just above 0 to 1. The formula is(rows with a value <= the current row's value) / rows_in_partition.
All three need an ORDER BY inside OVER to mean anything. PARTITION BY is optional and restarts the calculation for each group. They do not use a frame clause: each looks at the whole partition, so ROWS BETWEEN has no effect on them.
A sample table
The examples use one small table with ties on purpose. Run it to follow along.
CREATE TABLE exam_scores (
student VARCHAR(20),
score INT
);
INSERT INTO exam_scores (student, score) VALUES
('Ana', 95), ('Ben', 90), ('Cy', 90), ('Dee', 85),
('Eli', 80), ('Fay', 70), ('Gus', 70), ('Hal', 60);NTILE: equal-sized buckets
SELECT
student,
score,
NTILE(4) OVER (ORDER BY score DESC) AS quartile
FROM exam_scores;Eight rows in four buckets gives two rows per bucket.
| student | score | quartile |
|---|---|---|
| Ana | 95 | 1 |
| Ben | 90 | 1 |
| Cy | 90 | 2 |
| Dee | 85 | 2 |
| Eli | 80 | 3 |
| Fay | 70 | 3 |
| Gus | 70 | 4 |
| Hal | 60 | 4 |
When the rows do not divide evenly
If the row count is not a multiple of n, the first buckets each get one extra row. With NTILE(3) over these eight rows, 8 divided by 3 is 2 with remainder 2. The two leftover rows go to buckets 1 and 2, so the sizes are 3, 3 and 2. Bucket sizes therefore differ by at most one row.
If there are fewer rows than n, some buckets are empty. With 3 rows and NTILE(5), the rows get buckets 1, 2 and 3, and buckets 4 and 5 never appear.
NTILE splits ties
Ben and Cy both scored 90, yet Ben is in quartile 1 and Cy is in quartile 2. NTILE cares only about row position, not about values. Rows that tie on the ORDER BY columns can land in different buckets, and which one goes where is not guaranteed. The same happens to Fay and Gus.
If that is wrong for your use case, add a tiebreaker so the result is at least repeatable.
SELECT
student,
score,
NTILE(4) OVER (ORDER BY score DESC, student) AS quartile
FROM exam_scores;A tiebreaker makes the output deterministic. It does not make tied rows share a bucket. To keep equal values together, use CUME_DIST or PERCENT_RANK and cut on thresholds instead (see below).
PERCENT_RANK and CUME_DIST side by side
SELECT
student,
score,
RANK() OVER (ORDER BY score DESC) AS rnk,
CAST(PERCENT_RANK() OVER (ORDER BY score DESC) AS DECIMAL(5,3)) AS pct_rank,
CAST(CUME_DIST() OVER (ORDER BY score DESC) AS DECIMAL(5,3)) AS cume_dist
FROM exam_scores;The CAST only rounds the display. PostgreSQL has no ROUND(double precision, integer), so a cast is the portable way to round.
| student | score | rnk | pct_rank | cume_dist |
|---|---|---|---|---|
| Ana | 95 | 1 | 0.000 | 0.125 |
| Ben | 90 | 2 | 0.143 | 0.375 |
| Cy | 90 | 2 | 0.143 | 0.375 |
| Dee | 85 | 4 | 0.429 | 0.500 |
| Eli | 80 | 5 | 0.571 | 0.625 |
| Fay | 70 | 6 | 0.714 | 0.875 |
| Gus | 70 | 6 | 0.714 | 0.875 |
| Hal | 60 | 8 | 1.000 | 1.000 |
Check two rows by hand, with 8 rows in the partition:
- Dee has rank 4, so
PERCENT_RANK = (4 - 1) / (8 - 1) = 3/7 = 0.429. Four rows have a score at or above Dee's in this descending order (Ana, Ben, Cy, Dee), soCUME_DIST = 4/8 = 0.5. - Ben and Cy share rank 2. Both get
PERCENT_RANK = 1/7. ForCUME_DIST, both count as "at or before" each other, so each gets3/8.
How they differ
| Property | PERCENT_RANK | CUME_DIST |
|---|---|---|
| Based on | `RANK()` of the row | Position of the last peer row |
| First row value | Always 0 | `1/n` or higher |
| Last row value | Always 1 | Always 1 |
| Ties | Tied rows share the lower position | Tied rows share the higher position |
| Single-row partition | 0 | 1 |
A peer is a row that ties with the current row on every ORDER BY expression. CUME_DIST counts all peers, which is why tied rows jump together. PERCENT_RANK is a rescaled RANK, so it inherits the gaps that RANK leaves after ties.
Read CUME_DIST as "the fraction of rows at or before this one". Read PERCENT_RANK as "the fraction of the other rows strictly before this one", roughly.
Choosing between them
Some practical guidance:
- Use
NTILEfor reporting groups such as quartiles, deciles, or "top third". It guarantees the group count and near-equal sizes. - Use
CUME_DISTfor "top 10%" cut-offs, because ties stay together.WHERE cume_dist <= 0.1never splits equal values across the line. - Use
PERCENT_RANKwhen you want a normalised position that starts at 0 and ends at 1, for example to plot or compare across partitions of different sizes.
Filtering and aggregating on bucket results
These are window functions, so they cannot appear in WHERE. Compute them in a CTE and filter outside, as in the top-N pattern from earlier chapters.
WITH scored AS (
SELECT
student,
score,
CUME_DIST() OVER (ORDER BY score DESC) AS cd
FROM exam_scores
)
SELECT student, score
FROM scored
WHERE cd <= 0.5;This returns Ana, Ben, Cy and Dee, the top half with ties kept whole. To summarise each bucket, group on the bucket number in the outer query.
WITH bucketed AS (
SELECT
score,
NTILE(4) OVER (ORDER BY score DESC) AS quartile
FROM exam_scores
)
SELECT
quartile,
COUNT(*) AS students,
MIN(score) AS lowest,
MAX(score) AS highest,
AVG(score) AS average
FROM bucketed
GROUP BY quartile
ORDER BY quartile;Add PARTITION BY to do the same per group. For example, NTILE(4) OVER (PARTITION BY region ORDER BY amount DESC) gives each region its own quartiles.
Common errors and gotchas
- Forgetting the sort direction. With
ORDER BY score DESC, bucket 1 andPERCENT_RANK = 0belong to the highest score. With ascending order they belong to the lowest. Decide which end you mean by "top" before you write the query. - Treating NTILE buckets as value ranges. Bucket boundaries depend on row counts, not on score thresholds. The same score can fall in different buckets in different datasets, and tied scores can split.
- Dividing by zero in your head.
PERCENT_RANKover a one-row partition would divide by zero in the formula, so the standard defines the result as 0. Do not assume partitions have at least two rows. - Passing a bad argument to NTILE. The argument must be a positive integer. Zero or a negative number raises an error in most systems. PostgreSQL also accepts an expression that evaluates to an integer, but others may only accept a constant.
- Integer arithmetic when checking by hand. Writing
(rnk - 1) / (n - 1)with integer columns truncates to 0. Multiply by1.0first. - NULLs.
NULLvalues sort together, first or last depending on the database and onNULLS FIRSTorNULLS LAST. They take up positions and count inn, so they shift every percentile. Filter them out beforehand if they should not count.
Dialect notes
NTILE, PERCENT_RANK and CUME_DIST are supported in PostgreSQL, MySQL 8+, SQL Server, Oracle and SQLite 3.25+. Behaviour on the points below can vary, so test on your own system.
- Return types differ. Percent functions return floating-point in PostgreSQL and a decimal or float elsewhere, so format output explicitly.
- The
ORDER BYinsideOVERis optional forNTILEin some systems, but without it the bucket assignment is arbitrary. Always supply one. - Because these functions ignore frames, the default-frame pitfall that affects
LAST_VALUEdoes not apply to them.
Exercises
Exercise
Using the exam_scores table, how many rows does each bucket get with NTILE(3), and which buckets get the extra rows?
Show answer
Eight rows divided by three is 2 remainder 2. The first two buckets each get one extra row, so the sizes are 3, 3 and 2.
Exercise
Write a query that returns every student whose score is in the top 25% with ties kept together, using CUMEDIST. Which students does it return for examscores?
Show answer
WITH scored AS (SELECT student, score, CUMEDIST() OVER (ORDER BY score DESC) AS cd FROM examscores) SELECT student, score FROM scored WHERE cd <= 0.25; Only Ana qualifies (cd = 0.125). Ben and Cy have cd = 0.375, so they are excluded together. NTILE(4) would have put Ben in the first quartile and Cy in the second, splitting the tie.
Exercise
For a 5-row partition ordered by distinct values, what are the PERCENTRANK and CUMEDIST of the third row?
Show answer
PERCENTRANK = (3 - 1) / (5 - 1) = 0.5. CUMEDIST = 3 / 5 = 0.6.