Example 1
Assign eight students to four quartiles by test score
With 8 rows and NTILE(4), each bucket gets exactly 2 students. Bucket 1 contains the top two scores (Alice 95, Eve 91), bucket 2 the next two (Grace 88, Bob 82), and so on down to bucket 4 (Dave 65, Hank 55). If there were 9 students, the first bucket would receive 3 rows and the remaining three buckets 2 rows each.
CREATE TABLE test_scores (student VARCHAR(50), score INT);
INSERT INTO
test_scores
VALUES
('Alice', 95),
('Bob', 82),
('Carol', 78),
('Dave', 65),
('Eve', 91),
('Frank', 74),
('Grace', 88),
('Hank', 55);SELECT
student,
score,
NTILE (4) OVER (
ORDER BY
score DESC
) AS quartile
FROM
test_scores
ORDER BY
score DESC;| student | score | quartile |
|---|---|---|
| Alice | 95 | 1 |
| Eve | 91 | 1 |
| Grace | 88 | 2 |
| Bob | 82 | 2 |
| Carol | 78 | 3 |
| Frank | 74 | 3 |
| Dave | 65 | 4 |
| Hank | 55 | 4 |
The NTILE syntax is identical across all supported engines.