SQL random integer in a range
Generates a random integer between bounds: scale the engine's random float into [min, max+1), floor it, or call Oracle's two-argument VALUE directly.
- Catégorie
- Math
- Returns
integer- In this category
- 76 of 82
Syntaxe
FLOOR(RAND() * N) + 1
floor(random() * N)::int -- PostgreSQL
DBMS_RANDOM.VALUE(min, max) -- Oracle
Each block is a separate form. The support table and the examples show which engine takes which.
Prise en charge des moteurs
| Moteur | Support | Notes |
|---|---|---|
| SQL Server | Different name or syntax | FLOOR(RAND(CHECKSUM(NEWID())) * N) + 1 for per-row values; plain RAND() gives the same integer on every row |
| PostgreSQL | Oui | floor(random() * N)::int + 1 |
| MySQL | Oui | FLOOR(RAND() * N) + 1, or CEIL(RAND() * N) |
| SQLite | Oui | Use modulo of the 64-bit random(): ABS(random()) % N + 1 |
| Oracle | Oui | TRUNC(DBMS_RANDOM.VALUE(1, N + 1)): VALUE's high bound is excluded, so pass max + 1 |
Exemples
PostgreSQL
SELECT floor(random() * 6)::int + 1 AS die;
SQLite
SELECT ABS(random()) % 6 + 1 AS die;
Oracle
SELECT TRUNC(DBMS_RANDOM.VALUE(1, 7)) AS die FROM dual;
SQL Server
SELECT FLOOR(RAND(CHECKSUM(NEWID())) * 6) + 1 AS die FROM sys.objects;
Bon à savoir
- The float recipe is [min, min + N): multiply, floor, offset. FLOOR(RAND() * 6) + 1 is a die roll; forgetting the + 1 makes 0 possible and 6 impossible.
- SQLite's random() is a signed 64-bit integer, not a float; ABS(random()) % N + 1 is the idiom, and ABS guards the negative half of the range.
- Oracle's DBMS_RANDOM.VALUE(low, high) returns a float in [low, high); the high bound is excluded, so TRUNC(DBMS_RANDOM.VALUE(1, 7)) covers 1 through 6.
Questions about random range
How do I generate a random integer between 1 and N?
FLOOR(random_float * N) + 1: floor(random() * 6)::int + 1 on PostgreSQL, FLOOR(RAND() * 6) + 1 on MySQL, ABS(random()) % 6 + 1 on SQLite, TRUNC(DBMS_RANDOM.VALUE(1, 7)) on Oracle.
Why does my random integer include 0?
The offset was dropped: FLOOR(RAND() * 6) alone yields 0 through 5. Add 1 after the floor to shift to 1 through 6.
Why do all rows show the same random integer on SQL Server?
RAND() evaluated once per query. Use RAND(CHECKSUM(NEWID())) so each row reseeds the generator, as plain RAND() shares one value across the whole result set.
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.