SQL RANDOM function
Returns a random number. The traps are the spelling, SQLite returning an integer instead of a fraction, SQL Server's RAND() giving every row the same value, and the cost of ORDER BY RANDOM() on big tables.
- Категория
- Math
- Returns
float in [0, 1); a 64-bit integer on SQLite- In this category
- 8 of 82
Синтаксис
RANDOM() -- PostgreSQL, SQLite
RAND() -- MySQL, SQL Server
DBMS_RANDOM.VALUE -- Oracle
Each block is a separate form. The support table and the examples show which engine takes which.
Поддержка движка
| Движок | Support | Заметки |
|---|---|---|
| SQL Server | Different name or syntax | RAND(); evaluated once per query, not per row |
| PostgreSQL | Да | Supported under this name. |
| MySQL | Different name or syntax | RAND(), evaluated per row |
| SQLite | Да | RANDOM() returns a signed 64-bit integer, not a fraction |
| Oracle | Different name or syntax | DBMS_RANDOM.VALUE, a PL/SQL package function |
Примеры
PostgreSQL
SELECT FLOOR(RANDOM() * 100) AS dice; -- 0..99
SQL Server
SELECT TOP 10 * FROM orders ORDER BY NEWID();
PostgreSQL
SELECT * FROM events WHERE RANDOM() < 0.001; -- rough 0.1% sample
Полезно знать
- SQL Server's RAND() is evaluated once per query, so every row gets the same number. For a per-row value use RAND(CHECKSUM(NEWID())), or ORDER BY NEWID() to shuffle.
- SQLite's RANDOM() returns an integer between -9223372036854775808 and 9223372036854775807. For 0..n-1 use ABS(RANDOM()) % n; for a fraction use (RANDOM() / 18446744073709551616.0) + 0.5.
- ORDER BY RANDOM() sorts the whole table. For large tables sample instead: TABLESAMPLE SYSTEM (1) on PostgreSQL, TABLESAMPLE (1 PERCENT) on SQL Server, the SAMPLE clause on Oracle, or a WHERE RANDOM() < 0.01 filter on PostgreSQL.
- On PostgreSQL, MySQL and Oracle, FLOOR(RANDOM() * n) (or RAND(), DBMS_RANDOM.VALUE) gives an integer from 0 to n-1.
Questions about RANDOM / RAND
Why does RAND() return the same value on every row in SQL Server?
It is evaluated once for the whole query. RAND(CHECKSUM(NEWID())) gives a new value per row, because NEWID() is evaluated per row and seeds RAND each time.
Is ORDER BY RANDOM() okay?
For small tables, yes. For anything large it reads and sorts every row; use TABLESAMPLE (SQL Server), TABLESAMPLE SYSTEM or BERNOULLI (PostgreSQL), SAMPLE (Oracle), or an indexed random-key column instead.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Random sample of rows Dialect comparison
- Pick a random row Snippet
- Shuffled sample of rows Snippet
- Weighted random sample Snippet
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.