// SQL snippet

Weighted random sample

Sort by -LN(1 - RANDOM()) / weight: weighted sampling without replacement in one ORDER BY.

Main statement
PostgreSQL

The task

You want to sample orders where a 500-dollar order is ten times as likely to appear as a 50-dollar one, without duplicating rows by hand.

The snippet

Written for PostgreSQL.

PostgreSQL
SELECT id, amount
FROM orders
ORDER BY -LN(1 - RANDOM()) / amount
LIMIT 10;

Como funciona

Each row draws an exponential random variable with rate equal to its weight; sorting by that draw and taking the smallest values samples rows with probability proportional to weight. 1 - RANDOM() keeps the logarithm's argument strictly positive, because PostgreSQL's RANDOM() can return exactly 0 and LN(0) is an error. The weight must be greater than zero; filter out zero and NULL amounts first. The result is a weighted sample without replacement in one sort, no auxiliary tables.

Variations

One weighted pick via cumulative sums

WITH c AS (
  SELECT id, amount,
         SUM(amount) OVER (ORDER BY id) AS cum
  FROM orders
),
total AS (
  SELECT SUM(amount) AS grand FROM orders
)
SELECT c.id, c.amount
FROM c CROSS JOIN total
WHERE c.cum > RANDOM() * total.grand
ORDER BY c.cum
LIMIT 1;

Questions that come up

Does the weight have to be the amount column?

No, it can be any positive numeric expression, such as a count of purchases or a priority score. Weighted sampling only makes sense when the weights differ, otherwise it reduces to the plain shuffle.

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.