Select a random record with SQL server

Easy little trick, if you need to select a random record with SQL server as part of a query:

SELECT TOP 10 column,column FROM table ORDER BY newId()

Or could do:

SELECT TOP 10 percent column,column FROM table ORDER BY newId()

This is not brilliant for very large data sets, you can use TABLESAMPLE, for example:

SELECT column, column FROM table TABLESAMPLE (10 PERCENT)

Or:

SELECT column, column FROM table TABLESAMPLE (100 ROWS)

There is  caveat with TABLESAMPLE, it’s not fabulously random – and the number of rows returned may not match what you asked for, especially with small values, so if you ask for 10 records you might get back 20. And if you ask for 5 you might not see anything returned at all. I’m not entirely sure I’ve completely wrapped my head around TABLESAMPLE, you can read more on MSDN. But newId() is something I use all the time, and I’d stick with that unless you find your data set is large and the query is slow.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s