MS SQL Tips & Tricks

How to select X random records from a table

Let's say that the table we are going to use looks like that:

Images Table:

ID Image
1 Image1.jpg
2 Image2.jpg
3 Image3.jpg
4 Image4.jpg
5 Image5.jpg
6 Image6.jpg

We want to select 3 random images using one query. We can do that like this:

Select Top 3 ID, Image
From Images
Order by NEWID()

Remember that this method is going to scan whole table or whole index to get result, so use it on small amount of data. This method is available on MS SQL 2005.

Download SQL script

Learn more tricks

Add Comment