WIDTH_BUCKET Equal Width Histogram
Bucket amounts into equal-width ranges with WIDTH_BUCKET, which keeps out-of-range values in buckets 0 and n+1 rather than dropping them.
Code
-- WIDTH_BUCKET(amount, 0, 200, 4) 把 [0, 200) 等宽切成 4 个桶:
-- 低于 0 进 0 号桶,200 及以上进 5 号桶(n+1),不会丢弃任何一行
SELECT
WIDTH_BUCKET(amount, 0, 200, 4) AS bucket,
MIN(amount) AS bucket_min,
MAX(amount) AS bucket_max,
COUNT(*) AS orders
FROM orders
GROUP BY bucket
ORDER BY bucket;
-- 与 NTILE 的区别:NTILE 按行数等分(每桶行数接近、区间宽度不等),
-- WIDTH_BUCKET 按取值区间等分(每桶宽度相同、行数可以悬殊)
SELECT
NTILE(4) OVER (ORDER BY amount) AS ntile_bucket,
WIDTH_BUCKET(amount, 0, 200, 4) AS width_bucket
FROM orders;Inside the snippet
What runs here is SELECT — orders are the objects involved.
What the statements actually assemble: COUNT, MIN, MAX aggregation; a GROUP BY that collapses matching rows into one output row per group; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
What to watch for
- Window functions evaluate after
WHERE/GROUP BY, so filtering on their output in the same-levelWHEREwill not work — use an outer query or a CTE.
Putting it to use
The orders table is the working surface here.
Core lines
SELECT
WIDTH_BUCKET(amount, 0, 200, 4) AS bucket,
MIN(amount) AS bucket_min,
MAX(amount) AS bucket_max,
COUNT(*) AS orders
FROM orders
GROUP BY bucket
ORDER BY bucket;
SELECT
NTILE(4) OVER (ORDER BY amount) AS ntile_bucket,
WIDTH_BUCKET(amount, 0, 200, 4) AS width_bucket
FROM orders;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables or CTEs does it reference?
- `orders`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.