NTILE
Overview
NTILE(k) divides the ordered rows of each partition into up to k numbered buckets with sizes as balanced as possible. Larger buckets come first when the row count is not divisible by k. Buckets are based on row positions, not equal ranges of numeric values. Use a positive integer k and a stable ordering.
First example
SELECT id, team, NTILE(3) OVER (PARTITION BY team ORDER BY points DESC, id) AS bucketFROM window_scores ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, "A", 1 ], [ 2, "A", 1 ], [ 3, "A", 2 ], [ 4, "A", 2 ], [ 5, "A", 3 ], [ 6, "B", 1 ], [ 7, "B", 2 ], [ 8, "B", 3 ]]How it works
For five A rows and three buckets, the sizes are 2, 2, 1. In B, three rows occupy one bucket each. NTILE can divide tied scores between buckets: the two B scores of 60 occupy different buckets. If k exceeds the number of rows, not every bucket number appears. NTILE is not a continuous percentile calculation or a value threshold.
Practical example
SELECT id, NTILE(6) OVER (ORDER BY points DESC, id) AS bucketFROM window_scores WHERE team = 'B' ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 6, 1 ], [ 7, 2 ], [ 8, 3 ]]Practice and mistakes
Change k to 2 for A and predict sizes 3 and 2. Try k = 6 for B and observe only buckets 1, 2, 3. Use NTILE for balanced record segmentation, not for guarantees about equal scores. PostgreSQL 17 and SQLite support this function; the fixture results are tested only on SQLite.