Function Reference

NTILE

Splits the rows of a window partition into the given number of groups of roughly equal size and returns the group number of the row.

PostgreSQL 17.9
NTILE(number_of_groups)
number_of_groups
Number of groups, a positive integer
integer

Return value

An integer from 1 to number_of_groups

Examples

Three groups by birth date

PostgreSQL 17.9
SELECT member_name,
	birthday,
	NTILE(3) OVER (
		ORDER BY birthday
	) AS age_group
FROM FamilyMembers;
member_namebirthdayage_group
Headley Quincey1960-05-131
Ernest Forrest1961-09-111
Flavia Quincey1963-02-161
Constance Forrest1968-09-062
Andie Quincey1983-06-052
Lela Quincey1985-06-072
Annie Quincey1988-04-103
Wednesday Addams2005-01-133

Price quartiles in payments

PostgreSQL 17.9
SELECT payment_id,
	unit_price,
	NTILE(4) OVER (
		ORDER BY unit_price
	) AS price_quartile
FROM Payments;
payment_idunit_priceprice_quartile
1671
1971
1881
1581
1781
22101
26161
3202
27592
61002

Details

If the rows do not divide evenly, the first groups get one extra row: 8 rows split into 3 groups as 3, 3 and 2. If there are more groups than rows, each row gets its own group.

See also