Pattern
A histogram in SQL
Count values per bin of a fixed width, keeping the empty bins.
A value's bin is FLOOR(x / width) * width. Count per bin, then LEFT JOIN the counts onto every bin from
generate_series(0, last_bin, width) and COALESCE to 0: without the series, an empty bin disappears and the shape lies.
Choosing the width is the analysis: too wide hides the shape, too narrow shows noise.
WITH baskets AS (
SELECT o.order_id, SUM(l.quantity * l.unit_price) AS total
FROM orders o JOIN order_lines l ON l.order_id = o.order_id
GROUP BY o.order_id
)
SELECT CAST(FLOOR(total / 100) * 100 AS INTEGER) AS bin_start,
COUNT(*) AS orders,
repeat('█', CAST(FLOOR(COUNT(*) / 50) AS INTEGER)) AS bar
FROM baskets
GROUP BY 1
ORDER BY 1;
| bin_start | orders | bar |
|---|---|---|
| 0 | 2011 | ████████████████████████████████████████ |
| 100 | 420 | ████████ |
| 200 | 45 | |
| 300 | 17 | |
| 400 | 6 | |
| 500 | 1 |
Practise:A histogram in SQL