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()


  1. It appears as though the distribution from newid() is not truly random. When using it in my application, it definately favors a couple of values. This is because machine dependent items (such as the MAC) are used in generating GUIDs. This is probably not a huge deal in most apps (such as a random tip or product), but it kills my app that relies on a truly random distribution :-(.

    Comment by Mike — September 8, 2007 @ 1:57 PM

  2. What version of SQL Server are you using? Do you have any test app/example to play with?

    Comment by Alex Salamakha — September 9, 2007 @ 4:56 AM

RSS feed for comments on this post. TrackBack URL

Leave a comment

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