SQL SERVER RAND() Function to Generate Random Numbers

What is RAND() Function?

RAND() function in SQL is used to generate random numbers. It can create unique random numbers on execution. Let us check its usage in SQL Server.

Write the following SQL Snippet in query editor.

  1. SELECT RAND() as RandomNo  

 

Execute the preceding script and check the output.

output
We get a random number executing the preceding query. Please note the results will vary if you execute the same script in your SQL Server. Let us execute one more sql snippet to check more on random numbers.

Execute the following script,
  1. SELECT RAND() as RandomNo  
  2. UNION ALL  
  3. SELECT RAND() as RandomNo  
  4. UNION ALL  
  5. SELECT RAND() as RandomNo  
  6. UNION ALL  
  7. SELECT RAND() as RandomNo  
Let us check the output.

output

We get four different random numbers this time. We can implement RAND() function to generate random numbers in SQL in this manner.
Ebook Download
View all
Learn
View all