Blog Post

Selecting a Random Row From a Table

,

animals_hero_camels

A couple of times recently I’ve seen the question asked, ‘How can I select a single row at random from a table?’.

There are often a few ways of doing this suggested, most seem to rely using CTEs or temp tables.  I thought I’d share, in a quick post a very simple and easy way of doing it that I’ve used a couple of times.

SELECT TOP 1 *
FROM Table
ORDER BY NEWID() DESC

Obviously if you want to select more than one row, you can do so by simply changing TOP 1 to whatever you want it to be.

One word of warning however, this works nicely on smaller datasets but if you need to run this against a large dataset then you might find it could get a bit expensive.

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating