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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

width_bucket(value, low, high, count)

Parameters

ParameterDescription
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

One value
SELECT width_bucket(37, 0, 100, 4) AS bucket;

Output

 bucket
--------
      2
(1 row)

Run this on your computer — see “Get Started” for setup.

A salary histogram
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.

Was this page helpful?