WindowSQL standard

NTILE

Splits rows into the given number of groups of roughly equal size and numbers the groups.

Syntax

NTILE(<group count>) OVER (ORDER BY <sort key>)
NTILE(<group count>) OVER (PARTITION BY <group> ORDER BY <sort key>)

Deals ordered rows into N groups and tells you which group each row is in: 1, 2, …, N. If the rows don't divide evenly, the extra ones go to the first groups. That's how you split into halves, thirds or quarters: “the more expensive half of orders”, “the top 25% by salary”.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

orders

idcreated_atamount
12026-07-03 10:15:00120.50
22026-07-28 18:40:0080.25
32026-08-09 09:05:00199.99
42026-08-21 14:30:0045.00
52026-09-02 11:00:0064.75

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

Two halves by salary
SELECT name, salary,
NTILE(2) OVER (ORDER BY salary DESC) AS half
FROM employees;
namesalaryhalf
Olivia13501
Emma12001
Sophia12001
Liam10002
Noah9502

5 rows don't split evenly into two groups, so the first group is bigger: 3 and 2.

Three groups of orders by amount
SELECT id, amount,
NTILE(3) OVER (ORDER BY amount DESC) AS bucket
FROM orders;
idamountbucket
3199.991
1120.501
280.252
564.752
445.003
Only the more expensive half of ordersAdvanced
SELECT id, amount
FROM (
SELECT id, amount,
NTILE(2) OVER (ORDER BY amount DESC) AS half
FROM orders
) split
WHERE half = 1;
idamount
3199.99
1120.50
280.25

Watch out

The groups are equal in the number of rows, not in values. Equal amounts can end up in different groups, and group boundaries can fall anywhere.

If there are more groups than rows, some groups stay empty: NTILE(10) for 5 rows gives the numbers 1 to 5.

You can't use the result in the WHERE of the same query — calculate it in a subquery first and filter outside it.

Learn more in the course