sqlcmd.net validated sql reference
intermediate windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Bucket Rows Into Equal Groups With NTILE

Use `NTILE(n)` to divide an ordered result set into `n` roughly equal buckets and assign each row a bucket number.

Docker-validated Not currently validation-green

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.

Rows loaded before the example query runs.
Setup
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);
Shared across supported engines.
SQL
SELECT
  student,
  score,
  NTILE (4) OVER (
    ORDER BY
      score DESC
  ) AS quartile
FROM
  test_scores
ORDER BY
  score DESC;
Returned rows for the shared example.
studentscorequartile
Alice951
Eve911
Grace882
Bob822
Carol783
Frank743
Dave654
Hank554

The NTILE syntax is identical across all supported engines.

Where this command helps.

  • dividing customers into four equal quartiles by lifetime spend for targeted marketing
  • labelling the top 10% of scores for further analysis without hard-coding a threshold

What the command is doing.

NTILE(n) OVER (ORDER BY col) distributes rows into n numbered groups as evenly as possible. If the total number of rows does not divide evenly into n, the earlier buckets receive one extra row. The function assigns a bucket number — not a rank or row number — so all rows in the same bucket share the same number. Common uses include quartiles (NTILE(4)), deciles (NTILE(10)), and percentile bands for reporting and machine-learning feature engineering.