Selecting random rows from a Microsoft SQL database table

© copyright 03.Jan.2009 by Paul Bradley filed under Microsoft SQL Server


[Ad] need a break from coding?

Hoseasons Villas

There are lots of valid reasons why you would want to select random records from your Microsoft SQL Server database, for example you might want to randomly select three staff from your staff database as winners in the company staff lottery, or you may want to pull random adverts from your inventory of web site advertisers to display on your web site.

Using the NEWID function to select random records.

The example SQL code below is similar to what I use on my hotel web site to pull five random hotels from the Property table to display as featured hotels on the home page.


SELECT TOP 5 HotelName, Description, URL
	FROM Property ORDER BY NEWID()

 


If you have found this article helpful or useful please consider linking to it, emailing it to friends, or share it with others using social sites like del.icio.us, Stumble Upon or Twitter.

Paul Bradley

About the Author
Paul Bradley is a VB.NET software developer living and working in Cumbria. He provides PHP & MySQL bespoke development services via his software development company, Carlisle Software Limited.
He has over 20 years programming experience.

Other Popular Articles

Categories & Topics

Home · Apache · JavaScript · Perl · PDF · PHP · MySQL · MSSQL · TAR · Ubuntu Linux · Video · Visual Basic

Browse the complete article history, and if you like what you see; consider subscribing to the rss feed.