PostgreSQL 18 reference · Window Functions
PostgreSQL NTILE() Function
Split the rows of a window into N groups of nearly equal size and return each row's group number.
PostgreSQL 18 Since 8.4
Syntax
ntile(num_buckets) OVER (PARTITION BY ... ORDER BY ...)
Parameters
| Parameter | Description |
|---|---|
num_buckets |
The number of groups. |
Return value
integer from 1 to N.
Examples
SELECT quartile, count(*) AS people, min(salary) AS from_salary
FROM (SELECT salary, ntile(4) OVER (ORDER BY salary) AS quartile FROM employees) AS q
GROUP BY quartile
ORDER BY quartile;
Output
quartile | people | from_salary
----------+--------+-------------
1 | 3 | 65000
2 | 3 | 112000
3 | 2 | 150000
4 | 2 | 210000
(4 rows)Run this on your computer — see “Get Started” for setup.
SELECT name, ntile(2) OVER (ORDER BY price) AS half
FROM products
WHERE category_id = 2;
Output
name | half ---------------------+------ Wireless Mouse | 1 USB-C Hub | 1 Mechanical Keyboard | 2 4K Monitor | 2 (4 rows)
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| PostgreSQL 8.4 | Added |
In other languages
NTILE()· SQLite
Related
WIDTH_BUCKET()· Return which of n equal-width buckets a value falls into between a low and high bound, for building histograms.PERCENT_RANK()· Return a row's relative rank from 0 to 1: (rank - 1) / (rows in partition - 1).- SQL Window Functions · tutorial