Returning random rows in a result set

Using the NEWID() function to return random rows

The NEWID function will return a GUID value, that is statistically guaranteed to be unique e.g.

If you repeatedly call this function it will return a unique GUID. You can utilise this feature to give each row a unique random value. I’ve encountered a number of occaisions where it is desiranle to return from a resultset, a random number of rows. In the past I would achieve this by returning the result set to some application code that would randomise the results and select at most N items.

The example below shows how we can return 5 random rows from the Cutsomers table (Northwind database).

Selecting 5 Random rows

Each time the SQL snippet is run, 5 random customers are returned from the table.

This is a very neat and efficient.


One Response to Returning random rows in a result set

  1. Su00e6l vertu. Enn bu00edu00f0um viu00f0 hu00e9r u00ed Magrastru00e6ti eftir erfingjanum, skru00e1u00f0ur u00e1 fu00f6studaginn 13. ju00falu00ed:) u00 Click

Leave a Reply

Please log in using one of these methods to post your comment: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: