Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Random Sort

Tags:

sql-server

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

like image 569
Martynnw Avatar asked Sep 09 '08 21:09

Martynnw


People also ask

How do I randomly sort in SQL?

Using the unseeded RAND() function as a column in the SELECT statement returns the same value on every row as shown in the SortOrder column. To solve this problem, we need to pass a changing seed value to the RAND() function for every row to ensure that new random numbers are generated for each row.

Is newid () random?

SQL Server NewId() generates a random GUID or unique identifier which can be used to return randomized rows from a SELECT query. T-SQL developers will realize that the return list of a SQL SELECT query is sorted randomly when they place "NEWID() function in the "ORDER BY" clause of the SELECT statement.

What is Newid in SQL Server?

Using NEWID in a CREATE TABLE statement. Applies to: SQL Server. The following example creates the cust table with a uniqueidentifier data type, and uses NEWID to fill the table with a default value. In assigning the default value of NEWID() , each new and existing row has a unique value for the CustomerID column.


2 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) ; 
like image 195
Jon Galloway Avatar answered Sep 18 '22 17:09

Jon Galloway


select foo from Bar order by newid() 
like image 42
Jimmy Avatar answered Sep 20 '22 17:09

Jimmy