// SQL snippet

Shuffled sample of rows

A random sort plus LIMIT is a fair shuffle; TABLESAMPLE trades fairness for speed.

Main statement
PostgreSQL

The task

You want 100 random orders to eyeball data quality, freshly shuffled every run.

The snippet

Written for PostgreSQL.

PostgreSQL
SELECT id, customer_id, order_date, amount
FROM orders
ORDER BY RANDOM()
LIMIT 100;

它的運作方式

Assigning a random value to every row and sorting by it is a full shuffle, so the first 100 rows are an unbiased sample without replacement. The cost is the same sort as random-row, which is why very large tables prefer TABLESAMPLE or a precomputed random column. Each re-run produces a new sample because RANDOM() is re-evaluated per row per query.

Variations

Fast approximate sample: TABLESAMPLE

SELECT id, customer_id, order_date, amount
FROM orders TABLESAMPLE BERNOULLI (1)
LIMIT 100;

Questions that come up

Why did TABLESAMPLE return fewer than 100 rows?

TABLESAMPLE samples pages or row probabilities, not exact counts, so the row count varies per run and LIMIT 100 only caps it. If you need exactly N rows, keep the ORDER BY RANDOM() shuffle or retry.

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.