Function or operator · Advanced SQL

NTILE in SQL: Split sorted rows into groups

NTILE(N) splits the sorted rows into N groups of similar size. When the rows do not divide evenly, the larger groups come first.

Before continuing: This entry is part of the window functions guide. If you are new to the topic, start with OVER.

Example

The teaching database has nine products. Using NTILE(3), each group gets exactly three rows. We add id as a tiebreaker to make the order reproducible.

Products in three groups
SELECT
  id,
  name,
  price,
  NTILE(3) OVER (
    ORDER BY price DESC, id
  ) AS third_price
FROM products
ORDER BY price DESC, id;

How it is used

Picture a sorted line of people and N boxes. NTILE walks through that order and shares the rows out so the boxes are as close in size as possible. The result is a group label, not a mathematical percentage of the value.

“Quartile” is a practical label, not an exact statistical boundary. If there are many tied values, NTILE(4) can put rows with the same value into different groups, because its main goal is to balance the number of rows.

What changes from case to case

Restart the groups with PARTITION BY

If you want to classify within each category, department or customer, add PARTITION BY. Each partition gets its own groups 1…N.

NTILE by category
SELECT
  category,
  name,
  price,
  NTILE(2) OVER (
    PARTITION BY category
    ORDER BY price DESC, id
  ) AS half_in_category
FROM products
ORDER BY category, half_in_category, price DESC;

A category with a single row still gets group 1. If there are fewer rows than requested groups, some group numbers do not appear because there are no rows to assign to them.

NTILE, RANK and ROW_NUMBER answer different questions

FunctionQuestionEffect of ties
ROW_NUMBER()What sequential position does each row occupy?Every row gets a different number.
RANK()Where does this value rank relative to the others?Peers share a rank, and gaps appear.
NTILE(N)In which of N balanced groups does this row fall?It may split ties to balance the group sizes.

Avoid this confusion

Reading group 1 as «the top 25 %» without checking the data

With NTILE(4) the first group contains roughly a quarter of the rows, but not necessarily every value above a statistical threshold. Ties and the overall size matter.

Leaving out a tiebreaker when the result must be reproducible

If the ORDER BY leaves ties unresolved, the engine may order those rows in any way it likes. Add a stable key when the exact split matters.