// math reference

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.

Categoria
Math
Returns
integer
In this category
76 of 82

Sintaxe

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.

Suporte a mecanismos

MotorSupportNotas
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 Sim floor(random() * N)::int + 1
MySQL Sim FLOOR(RAND() * N) + 1, or CEIL(RAND() * N)
SQLite Sim Use modulo of the 64-bit random(): ABS(random()) % N + 1
Oracle Sim TRUNC(DBMS_RANDOM.VALUE(1, N + 1)): VALUE's high bound is excluded, so pass max + 1

Exemplos

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;

Bom saber

  • 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.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.