Random Numbers in SQL

If you need to generate random number in SQL. Sql Server has the RAND() function.

The RAND() function will return a random float value. It can also take a TINYINT, SMALLINT, or INT number as a seed value. When a seed value is used, RAND() will always return the same value.

For example:

SELECT RAND(5) AS [Seeded_Rand],RAND(5) AS [Seeded_Rand], RAND(5) AS [Seeded_Rand]

Will return the same float for all three calls

SELECT RAND() AS [NonSeeded_Rand],RAND() AS [NonSeeded_Rand],RAND() AS [NonSeeded_Rand]

Different float values for each one

How to get a random number between an upper and lower limit

This will give a random number between 0 and 100

DECLARE @MinNumber AS INT = 10;
DECLARE @MaxNumber AS INT = 50;

SELECT @MinNumber + FLOOR(RAND() * ( @MaxNumber + 1 - @MinNumber)) AS [Between_10_and_50];

Random Int from 0 to an upper limit of x

DECLARE @UpperLimit AS INT = 100;
SELECT ROUND(RAND() * @UpperLimit, 0) AS [From_0_Up_To_100];