// SQL snippet

Percentile buckets

Compute the cut points once, then bucket every row with a CASE.

Main statement
PostgreSQL

The task

You want every order tagged with a size band, where the bands come from the data's own quartiles rather than hard-coded thresholds.

The snippet

Written for PostgreSQL.

PostgreSQL
WITH cutoffs AS (
  SELECT PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY amount) AS p25,
         PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY amount) AS p50,
         PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY amount) AS p75
  FROM orders
)
SELECT o.id, o.amount,
       CASE
         WHEN o.amount <= c.p25 THEN 'low'
         WHEN o.amount <= c.p50 THEN 'medium'
         WHEN o.amount <= c.p75 THEN 'high'
         ELSE 'top'
       END AS size_band
FROM orders o
CROSS JOIN cutoffs c
ORDER BY o.amount;

How it works

The cutoffs CTE computes the three quartiles of all amounts in one scan; the CROSS JOIN attaches them to every row as constants. The CASE buckets each amount against them. PERCENTILE_CONT interpolates between values, giving smooth cut points; PERCENTILE_DISC returns an actual amount from the data if you prefer thresholds that really exist.

Variations

Portable quartiles with NTILE

WITH banded AS (
  SELECT id, amount,
         NTILE(4) OVER (ORDER BY amount) AS quartile
  FROM orders
)
SELECT id, amount,
       CASE quartile
         WHEN 1 THEN 'low'
         WHEN 2 THEN 'medium'
         WHEN 3 THEN 'high'
         ELSE 'top'
       END AS size_band
FROM banded
ORDER BY amount;

Questions that come up

Why are the bands not exactly 25% of rows each?

PERCENTILE_CONT buckets by value, and ties on the same amount all fall in the same band however many rows they contain. NTILE buckets by row count, so it guarantees quartile sizes but its cut points shift with ties.

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.