SQL Server Random Sort

Viewed 58377

What is the best way to sort the results of a sql query into a random order within a stored procedure?

4 Answers

This is a duplicate of SO# 19412. Here's the answer I gave there:

select top 1 * from mytable order by newid()

In SQL Server 2005 and up, you can use TABLESAMPLE to get a random sample that's repeatable:

SELECT FirstName, LastName FROM Contact TABLESAMPLE (1 ROWS) ;
select foo from Bar order by newid()

You can't just ORDER BY RAND(), as you know, because it will only generate one value. So use a key for a seed value.

SELECT RAND(object_id), object_id, name
  FROM sys.objects
 ORDER BY 1
Related