Wednesday, 28 March 2007

Select a random row from a table

It looks like a simple task to read a random record from a table. Many people would spend lot of time try to do this with lot of t-sql code. When I was reading an article, I found this could be easiely achieved by using NewID() function. The use of this function is like this:

SELECT TOP 3 newid(), ProductID, ProductName
FROM Products
order by newid()

Each time you execute this sql, the result will be 3 random records. And you can select one record back by limiting TOP 1.

No comments: