KeyLimeTie Blog

Randomize your data with ease - SQL Server

By Brian Pautsch – 3/21/2006 8:31:56 PM. Posted to Code Snippets.

Often, I have the need to randomize what's presented to the user. For a test taking application I wrote, each student's test questions had to be randomized (helps prevent cheating). For a community website I built, the website's homepage sponsors had to be randomized each time the page was displayed. I've seen people try to solve this all kinds of ways, but there's one VERY simply way to do it...use SQL Server GUIDs.

Let's say you have a table of Sponsors with a SponsorID (int, identity, primary key) and a SponsorImage (varchar(50)).




And you have the following sponsor data:




To get the data returned in a randomized order, run the following query:

SELECT *, NEWID() AS RandomNum
FROM Sponsors
ORDER BY RandomNum



As you can see, the GUID is auto-generated and when sorted upon gives a different sort orderĀ for the sponsors. Could it be any easier?

Comments

Leave a Comment

Name:
Email:
URL:
Comment:
Security Code:
Type Security Code:

Photos on Flickr

More Photos »

Search Blog


Get Email Updates

Like what you read here at KeyLimeTie? Sign up for our email list!

Subscribe