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.
ORDER BY random() works on every engine and gets slower with every row you add.
Filed under Querying
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.
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.
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.
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.
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.
SELECT * FROM users ORDER BY random() LIMIT 10;
No sampling clause; ORDER BY random() is the only built-in option.
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.
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.
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.
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.
Five engines, two spellings of "give me rows 21 to 30", plus Oracle's old ROWNUM wrapper.
One portable window function, and two Oracle and SQLite features that look similar but do something else.
The same query written three ways, depending on the engine.
SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.