// dialect comparison

Random sample of rows

ORDER BY random() works on every engine and gets slower with every row you add.

Filed under Querying

The verdict

ORDER BY random() with a row cap is portable and returns exactly N rows, but it reads and sorts the whole table, which is fine up to a few hundred thousand rows. For bigger tables use the engine's sampler (TABLESAMPLE or SAMPLE) and accept an approximate size, or keep an indexed random-key column.

Where they differ

The quick form gives every row a random sort key and keeps the first N. The scalable form samples pages or a percentage of rows (TABLESAMPLE in SQL Server and PostgreSQL, SAMPLE in Oracle) and returns roughly, not exactly, the size you asked for.

How each engine writes it

SQL Server

SELECT TOP 10 * FROM users ORDER BY NEWID();

Sorts the whole table by a fresh GUID. TABLESAMPLE (1 PERCENT) reads whole pages cheaply, so the row count varies and rows cluster.

PostgreSQL

SELECT * FROM users ORDER BY random() LIMIT 10;

Same full-table cost. TABLESAMPLE BERNOULLI (1) samples 1% of rows and SYSTEM (1) 1% of pages; both scale to huge tables.

MySQL

SELECT * FROM users ORDER BY RAND() LIMIT 10;

No sampling clause. RAND() is computed for every row before the sort, so this is fine on small tables and slow on big ones.

SQLite

SELECT * FROM users ORDER BY random() LIMIT 10;

No sampling clause; ORDER BY random() is the only built-in option.

Oracle

SELECT * FROM users ORDER BY DBMS_RANDOM.VALUE FETCH FIRST 10 ROWS ONLY;

12c+; before that, wrap the sorted query and filter ROWNUM <= 10. SAMPLE (1) keeps about 1% of rows but still scans the table; SAMPLE BLOCK (1) reads about 1% of blocks.

Questions that come up

Why is ORDER BY random() slow on large tables?

The engine has to generate a random key for every row before it can know which ten are smallest, so the cost grows with the table, not with N. A top-N sort keeps memory small, but the full scan remains.

How do I get exactly N rows fast from a huge table?

Oversample, then cap: SELECT * FROM users TABLESAMPLE SYSTEM (1) LIMIT 10 in PostgreSQL may return fewer than 10 on a small table, so retry or sample more. Or store an indexed random_key column and query WHERE random_key >= :r ORDER BY random_key LIMIT 10.

Does TABLESAMPLE give each row an equal chance?

BERNOULLI includes each row independently with probability p. SYSTEM picks whole pages, so every row still has probability p but rows from the same page arrive together, which skews small samples. SQL Server's TABLESAMPLE is page-based like SYSTEM.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.