// SQL snippet

Build a value-distribution histogram

Divide the value by the bin width, floor it to a bin number, and count rows per bin: a histogram in one GROUP BY.

Main statement
All engines

The task

A raw MIN/MAX of orders.total says nothing about shape. Fixed-width buckets show whether totals cluster low, trail long, or have suspicious spikes at round numbers.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT bucket * 50 AS bucket_start,
       bucket * 50 + 50 AS bucket_end,
       COUNT(*) AS order_count
FROM (
  SELECT FLOOR(total / 50.0) AS bucket
  FROM orders
  WHERE total IS NOT NULL
) b
GROUP BY bucket
ORDER BY bucket;

Como funciona

FLOOR(total / 50.0) maps each total to its 50-wide bin number, and multiplying back gives the bin's edges: a bin covers bucket_start up to but not including bucket_end, so 49.99 lands in 0-50 and 50.00 in 50-100. Dividing by 50.0 rather than 50 matters on SQLite, SQL Server and PostgreSQL when the column is an integer: integer division truncates toward zero, which would put -5 in the 0 bin instead of -50. The bin number is computed in a derived table and grouped there, because MySQL's ONLY_FULL_GROUP_BY mode rejects SELECT FLOOR(total / 50) * 50 ... GROUP BY FLOOR(total / 50). Halve the width for finer grain, double it to zoom out.

Variations

Equal-depth buckets with NTILE

WITH buckets AS (
  SELECT total, NTILE(10) OVER (ORDER BY total) AS decile
  FROM orders
  WHERE total IS NOT NULL
)
SELECT decile,
       MIN(total) AS lowest_in_bucket,
       MAX(total) AS highest_in_bucket,
       COUNT(*) AS order_count
FROM buckets
GROUP BY decile
ORDER BY decile;

Questions that come up

Why does NULL disappear from the histogram?

It would not disappear on its own: FLOOR(NULL / 50.0) is NULL, and GROUP BY puts all NULLs into one extra bin with no edges, which charts badly. The WHERE total IS NOT NULL drops them on purpose. If the NULL count matters, report it separately with COUNT(*) - COUNT(total).

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.