// math reference

SQL WIDTH_BUCKET function

Returns the 1-based bucket number of a value within an equal-width histogram: WIDTH_BUCKET(15, 0, 100, 4) is 1 for the 0-25 bucket.

類別
Math
Returns
integer
In this category
72 of 82

語法

WIDTH_BUCKET(value, min, max, buckets)

引擎支援

引擎Support備註
SQL Server Not built in No WIDTH_BUCKET; emulate with 1 + FLOOR((x - min) * n / (max - min))
PostgreSQL 是 Built in; also WIDTH_BUCKET(x, thresholds[]) for uneven buckets
MySQL Not built in No built-in; the floor formula works
SQLite Not built in No built-in; the floor formula works
Oracle 是 Built in, same argument order

範例

PostgreSQL

SELECT WIDTH_BUCKET(15, 0, 100, 4) AS bucket;  -- 1

Oracle

SELECT WIDTH_BUCKET(60, 0, 100, 4) AS bucket FROM dual;  -- 3

PostgreSQL

SELECT WIDTH_BUCKET(age, 0, 100, 10) AS decade, COUNT(*)
FROM users GROUP BY 1 ORDER BY 1;

小知識

  • Values below min go to bucket 0 and values at or above max go to buckets + 1: out-of-range values do not error, they clip to the edges, so GROUP BY will show those buckets too.
  • The min bound is inclusive, the max bound exclusive: WIDTH_BUCKET(100, 0, 100, 4) is 5, not 4.
  • Buckets are equal-width, not equal-count: for percentile bins you want NTILE or PERCENTILE_CONT instead.

Questions about WIDTH_BUCKET

What does WIDTH_BUCKET return for out-of-range values?

0 for values below min, buckets + 1 for values at or above max. Nothing errors. That makes GROUP BY bucket self-documenting, with the edge buckets showing stragglers.

Is the max bound included in the last bucket?

No. The interval is [min, max): WIDTH_BUCKET(100, 0, 100, 4) returns 5, one past the last bucket. Only values strictly below max land in bucket 4.

How is WIDTH_BUCKET different from NTILE?

WIDTH_BUCKET bins by value ranges; NTILE bins by row count. Equal-count buckets (quartiles of rows) are NTILE; equal-width ranges of the value are WIDTH_BUCKET.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.