Monday, May 9, 2016

SQL Server: Retrieving Rows in a Random Order

Here's a simple trick to retrieve rows in a random order every time:
  1. SELECT ...  
  2.  FROM ...  
  3. WHERE ...  
  4. ORDER BY RAND(ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)))  

Unlike MySQL, SQL Server returns the same random numbers if a new seed is not specified. Since NEWID() includes the random portions, it is possible to use it for the purpose.

No comments:

Post a Comment