How to Generate a Random Number within a Specific Range Using SQL Query

← PrevNext →

To generate a random number between a given range in SQL Server, you can use the RAND() function along with some mathematical calculations.

Example:

Here's an SQL query to generate a random number between a specified minimum and maximum range.

  DECLARE @MinValue INT = 1;		-- Minimum value.
  DECLARE @MaxValue INT = 10;		-- Maximum value.

  SELECT FLOOR(@MinValue + (RAND() * (@MaxValue - @MinValue + 1))) AS RandomNumber;

• The RAND() function generates a random floating-point number between 0 and 1. For example,

SELECT RAND()  -- Output: Some floating value like... 0.354830328267619

• Variable @MinValue is the minimum value of the range.

• Variable @MaxValue is the maximum value of the range.

• The Floor() function is used to round of the result to the nearest number (integer).

← PreviousNext →