Advanced · Lesson 10 of 18

NTILE - Dividing into Buckets

NTILE(n) divides rows into n roughly equal groups (buckets), numbered 1 through n.

Split employees into 4 salary quartiles:

SELECT first_name, salary,
       NTILE(4) OVER (ORDER BY salary) AS quartile
FROM employees;

Quartile 1 = bottom 25%, Quartile 4 = top 25%.

Common uses:

  • NTILE(4) for quartiles
  • NTILE(3) for low/medium/high groups
  • NTILE(10) for deciles (percentile buckets)
  • NTILE(100) for exact percentiles

Works with PARTITION BY too: NTILE(3) OVER (PARTITION BY department_id ORDER BY salary) -- separate buckets per department

Unlike RANK, NTILE always creates evenly-sized groups. If 10 rows split into 3 groups: groups of 4, 3, 3.

Check your understanding

Which function divides rows into N equal-sized buckets?

Examples run on the employees sample database. Open any of them in the playground to experiment.