alex in a nutshell

July 15, 2007

Random sort in T-SQL

Filed under: — Alex Salamakha @ 8:29 PM

Recently I had a task to return rows from a SQL Server database in random order.

Here is a simple solution:

SELECT * FROM MyTable ORDER BY newid()

Potential applications include selecting a random tip of the day or a random product of the day for any portal/online shop/etc, which is now simple enough by typing the following:

SELECT TOP 1 * FROM MyTable ORDER BY newid()

Copyright © 1997-2017 Alexei Salamakha. All rights reserved
email: alex@salamakha.com    Alex Salamakha on Facebook    Alex Salamakha on LinkedIn