// SQL snippet

Pick a random row

ORDER BY RANDOM() is the simple answer; TABLESAMPLE is the fast one.

Main statement
PostgreSQL
다음도 지원
SQL Server MySQL

The task

You want one random order to feature on a dashboard. Sorting the whole table feels heavy, and it is, but for most tables it is fine.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

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

작동 방식

The engine computes a random value per row, sorts by it, and LIMIT 1 keeps the winner. That is a full scan plus a sort (PostgreSQL uses a top-1 heap, so memory stays small, but every row is still read). The statement runs unchanged on SQLite; elsewhere only the function and row-limit syntax change: MySQL uses RAND(), SQL Server NEWID() with TOP (1), Oracle ORDER BY DBMS_RANDOM.VALUE FETCH FIRST 1 ROW ONLY.

Variations

MySQL: RAND()

MySQL
SELECT id, customer_id, order_date, amount
FROM orders
ORDER BY RAND()
LIMIT 1;

SQL Server: NEWID()

SQL Server
SELECT TOP (1) id, customer_id, order_date, amount
FROM orders
ORDER BY NEWID();

Big tables: TABLESAMPLE (PostgreSQL)

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

Questions that come up

How do I get a random row from a very large table cheaply?

TABLESAMPLE SYSTEM (1) reads about 1% of the table's pages and LIMIT 1 takes the first row it finds, so it is fast but rows on the same page are favoured together, and a small table can return nothing. SQL Server spells it TABLESAMPLE (1 PERCENT) with TOP (1), Oracle SAMPLE (1). Another trick is picking a random id in the known range and taking the first row with id >= that value; gaps from deleted ids make the rows after a gap more likely.

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.