You know that RAND() function in SQL Server generates a random float value 0 through 1 (excluding 0 and 1).

Let us create the following dataset
CREATE TABLE #random(no INT) INSERT INTO #random(no) SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 3
If you want to generate a random value, you can use the following code
SELECT no, RAND() AS random_number FROM #random
which results to
no random_number 1 0.370366365964781 1 0.370366365964781 1 0.370366365964781 2 0.370366365964781 3 0.370366365964781 3 0.370366365964781
Please note that when you execute it , you may get different random number than what I got for column 2 but all will be same
What if you want to generate random number in such a way that it is reset to each column value (in this case the column is no)?
Did you know that RAND() accepts a seed value as well?
If you execute the following code,
SELECT no, RAND() AS random_number,RAND(no) AS random_number_reset FROM #random
the result is
no random_number random_number_reset 1 0.58334760467751 0.713591993212924 1 0.58334760467751 0.713591993212924 1 0.58334760467751 0.713591993212924 2 0.58334760467751 0.713610626184182 3 0.58334760467751 0.71362925915544 3 0.58334760467751 0.71362925915544
Please note that when you execute it , you may get different random number than what I got for column2 2 and 3. If you notice the result the values of second column is same for all rows, whereas the values of third column is same withing a group (column no), and different across groups. So if you want to generate random number differently for each group, you can make use of this method.
Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.
Discover more from SQL Authority with Pinal Dave
Subscribe to get the latest posts sent to your email.





4 Comments. Leave new
Sir How do i Delete Two Table Data at a time?
Asset Number Table ID AssetProperty Table AssetNumberID
please post table create table statement and exact requirements.
This is a really bad advise. If you give seed to rand(), then the result is NOT random, it is always the same number with the same seed.
Pertsa – Yeah, I didn’t ask to use seed.