Running the above SELECT statement generated the following result set:
CustomerID CompanyName ContactName
---------- ---------------------------------------- ------------------------------
ALFKI Alfreds Futterkiste Maria Anders
ANATR Ana Trujillo Emparedados y helados Ana Trujillo
ANTON Antonio Moreno Taquería Antonio Moreno
AROUT Around the Horn Thomas Hardy
BERGS Berglunds snabbköp Christina Berglund
Running it over and over again generated the same result set. If the
RAND() system function is supposed to generate random numbers when executed,
how come the result set generated are all the same? To investigate this
further, let's include the result of the RAND() system function as part of the
result set.
SELECT TOP 5 RAND() AS [Random], [CustomerID], [CompanyName], [ContactName]
FROM [dbo].[Customers]
ORDER BY RAND()
Executing this SELECT statement generated the following result set (please note
again that the results shown here will be different from the results you will
get, particularly to the first column).
Random CustomerID CompanyName ContactName
------------------- ---------- ---------------------------------- ------------------
0.73381230186299884 ALFKI Alfreds Futterkiste Maria Anders
0.73381230186299884 ANATR Ana Trujillo Emparedados y helados Ana Trujillo
0.73381230186299884 ANTON Antonio Moreno Taquería Antonio Moreno
0.73381230186299884 AROUT Around the Horn Thomas Hardy
0.73381230186299884 BERGS Berglunds snabbköp Christina Berglund
As can be seen from the output, the output generated by the RAND() system
function are all the same. If the RAND() system function is supposed to
generate random values, how come it's generating the same value when executed
in a SELECT statement?
The answer lies in the SQL Server's Books Online. According to Books
Online under the RAND functions topic:
"Repetitive invocations of RAND() in a single query will produce the same
value."
This is the reason why the same value is returned in the SELECT statement above
for the RAND() column.
Conclusion
In conclusion, the only way to generate a random number of records from any
table is to combine the TOP clause and the ORDER BY NEWID() in the SELECT
statement.