SQL Server RAND() Function
Definition and Usage
The RAND()
function in SQL Server generates a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive). Whether it produces truly random numbers or a repeatable sequence depends on whether a seed value is provided.
Syntax
Syntax
RAND ( seed )
Parameter Values
Parameter | Description |
---|---|
seed |
Optional. An integer value used as a seed. If provided, RAND() will generate the same sequence of random numbers each time it's called with that seed. If omitted, a different random number is generated each time. |
Examples
Example 1: Generating a Random Number (No Seed)
This example demonstrates generating a random decimal number between 0 and 1 without using a seed value.
SQL Query
SELECT RAND();
Output
-- Output will vary. Example:
-- Column1
-- -----------
-- 0.73654987
Example 2: Generating a Random Number (With Seed)
This example uses a seed value (6) to generate a repeatable sequence of random numbers.
SQL Query
SELECT RAND(6);
Output
-- Output will be the same every time with seed 6. Example:
-- Column1
-- -----------
-- 0.417022
Example 3: Generating a Random Number within a Range (5 to 10, exclusive of 10)
This example demonstrates how to generate random numbers within a specific range (5 to 10, excluding 10).
SQL Query
SELECT RAND()*(10-5)+5;
Output
-- Output will vary, but always between 5 and 10 (exclusive of 10). Example:
-- Column1
-- -----------
-- 7.283749
Example 4: Generating a Random Integer within a Range (5 to 10, inclusive)
This example generates random integers between 5 and 10 (inclusive).
SQL Query
SELECT FLOOR(RAND()*(10-5+1)+5);
Output
-- Output will vary, but always an integer between 5 and 10 (inclusive). Example:
-- Column1
-- -----------
-- 8
Technical Details
The RAND()
function is available in SQL Server 2008 and later, Azure SQL Database, and Azure SQL Data Warehouse.