Thursday, September 15, 2005

How to return random results from SQL SERVER

Sometimes you want to display 4 random articles/pics/you name it on your web page and you don’t want to write a lot of code.
SQL SERVER 2000 has a neat little function called NEWID() that can help you out.
Run the code below from Query Analyzer and keep hitting F5.
You will see that the results will be different every time.

USE pubs

SELECT top 4 * FROM dbo.authors
ORDER BY NEWID()

Note: this does not work in SQL SERVER 7

1 comment:

Anonymous said...

Bloody hell, thats handy for randomised mailshots for customer surveys...