Returning a Random Result Set Using Order By

The Order By Clause is generally used to make data sets a little tidier, but a lesser known fact is that it can also be used to return a random set of data!

An Order By will always be placed at the very end of your SQL statement:

SELECT * 
 
FROM People
 
ORDER BY FirstName, SecondName ASC

The above statement will order the result set by FirstName in ascending (Smallest to Largest, A-Z) order, then by SecondName. For example, John Adams would be ahead of John Smith in the result set.

If you would like to order the result set from Largest to Smallest or Z-A, simply add DESC (For Descending) in place of ASC.

You don’t have to specify ASC or DESC at the end, but in not doing so, SQL Server will assume the default behaviour which is ascending.

The ORDER BY can also be used to specify that you would like to return a random result set. This is usually used in conjunction with a TOP Clause:

SELECT TOP 10 * 
 
FROM Person
 
ORDER BY NEWID()

The above will select the top 10 rows from within the Person table, but because we have specified ORDER BY NewId(), we’ll return a different set of 10 rows each time the query is run.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)