SQL random values per row
How to get a different random number on every row: the engines that do it natively and the SQL Server workaround for RAND()'s once-per-query evaluation.
- 类别
- Math
- Returns
float in [0, 1)- In this category
- 75 of 82
语法
random() -- per row
RAND() -- once per query on SQL Server
RAND(CHECKSUM(NEWID())) -- per row on SQL Server
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() evaluates once per SELECT: every row gets the same value; RAND(CHECKSUM(NEWID())) recomputes per row |
| PostgreSQL | 是 | random() is evaluated per row |
| MySQL | 是 | RAND() is evaluated per row |
| SQLite | 是 | random() is evaluated per row |
| Oracle | 是 | DBMS_RANDOM.VALUE is evaluated per row |
示例
SQL Server
SELECT RAND(CHECKSUM(NEWID())) AS per_row FROM sys.objects; -- different on each row
SQL Server
SELECT RAND() AS same_everywhere FROM sys.objects; -- one value, every row
PostgreSQL
SELECT random() AS per_row FROM generate_series(1, 3); -- three different values
值得了解
- SQL Server's RAND() is the trap: SELECT RAND() FROM big_table returns the identical value on every row, evaluated once for the statement.
- The per-row SQL Server idiom is RAND(CHECKSUM(NEWID())): NEWID() differs per row, its checksum reseeds the generator, and the value varies.
- Per-row random values make ORDER BY random() a full shuffle: fine on small tables, a scan and sort of every row on large ones.
Questions about RAND per row
Why does RAND() return the same value on every row in SQL Server?
T-SQL evaluates RAND() once per query and shares the value across rows. For per-row randomness use RAND(CHECKSUM(NEWID())), whose seed changes with each row's NEWID().
Does MySQL's RAND() differ per row?
Yes. Unlike SQL Server, MySQL evaluates RAND() per row, as PostgreSQL's random() and SQLite's random() and Oracle's DBMS_RANDOM.VALUE do.
How do I pick n random rows?
ORDER BY random() LIMIT n on PostgreSQL and SQLite, ORDER BY RAND() LIMIT n on MySQL, SELECT TOP (n) ... ORDER BY NEWID() on SQL Server, and ORDER BY DBMS_RANDOM.VALUE FETCH FIRST n ROWS ONLY on Oracle. All of them sort the whole table; TABLESAMPLE is cheaper on big tables.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
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.