SQL Server RAND() Function

In SQL Server, the RAND() function is used to generate a random number. The function returns a random floating-point number between 0 and 1.

Syntax

RAND()

Usage

The RAND() function can be used in various scenarios, such as generating test data, random sorting, and more.

Examples

Here are two examples of using the RAND() function:

Example 1

Assume there is a student table containing the following data:

name age gender
John 20 M
Mary 21 F
Tom 19 M
Lily 20 F

Now, we want to randomly select one student’s information. We can use the following SQL statement:

SELECT TOP 1 * FROM student ORDER BY `RAND()`;

Running this statement may result in the following:

name age gender
Tom 19 M

Example 2

Assume we want to generate an array containing 5 random numbers. We can use the following SQL statement:

SELECT `RAND()`, `RAND()`, `RAND()`, `RAND()`, `RAND()`;

Running this statement may result in the following:

(No column name) (No column name) (No column name) (No column name) (No column name)
0.7944843580975 0.42869104224624 0.16941075511145 0.80730458489609 0.2711461038008

Conclusion

The RAND() function is used in SQL Server to generate a random number and can be used in various scenarios, such as generating test data, random sorting, and more.