PostgreSQL 18 reference · Math Functions
PostgreSQL WIDTH_BUCKET() Function
Return which of n equal-width buckets a value falls into between a low and high bound, for building histograms.
PostgreSQL 18
Syntax
width_bucket(value, low, high, count)
Parameters
| Parameter | Description |
|---|---|
value |
The value to place. |
low, high |
The range to divide. |
count |
The number of buckets. |
Return value
An integer from 0 (below low) to count + 1 (at or above high).
Examples
SELECT width_bucket(37, 0, 100, 4) AS bucket;
Output
bucket
--------
2
(1 row)Run this on your computer — see “Get Started” for setup.
SELECT width_bucket(salary, 50000, 250000, 4) AS bucket, count(*) AS people
FROM employees
GROUP BY bucket
ORDER BY bucket;
Output
bucket | people
--------+--------
1 | 3
2 | 3
3 | 2
4 | 1
5 | 1
(5 rows)Run this on your computer — see “Get Started” for setup.
Related
FLOOR()· Round a number down to the nearest integer: floor(2.9) is 2 and floor(-2.1) is -3.NTILE()· Split the rows of a window into N groups of nearly equal size and return each row's group number.- SQL Aggregate Functions · tutorial