How to randomly select records from SQL Server?
Hi all SQLers!
Last week I’ve found this quiz from my consultant customer. He has a scenario to let me help as a short describe here.
How do I select some records from SQL Server randomly?
It seems to be an easy question but what we can do if SQL Server doesn’t directly support this functionality! So, I decide to read on SQL Server’s online help to find out the solution and result on SQL Server don’t have any function that can select records randomly.
Now I’m thinking about Joe Celko, the person who you know when thinking about SQL puzzle or quiz. Just thinks to him but didn’t try to contact him cause I still believe this quiz gonna be too easy for him to implement.
So, I just continue on research…
After that, I seen many various methods to implement this functionality but most of them are implement at application level. Means your application just select all records and randomize some number then select the records randomly by indexing access. That I thinks not efficiency. Certainly, you feel the same as me or you’ll not reading until this. ^_^
In last weekend, while I’m finding for the best solution for this case. My friend come along to my home and talking about SQL Server and blah blah blah… and then he gave me an idea to solve this case. For god sake, this is a solution not an idea!
How the solution be and how it works?
The key just stay in NEWID() function!
For all people who don’t know what is NEWID() function. This is a built-in function in SQL Server that will generate a unique string which will not the same on each call. Just try it in SQL Server by executing this command. “SELECT NEWID()“.
Gotcha! It’s what someone called “unique identifier”, “GUID” or somethings else.
So now, how can I use this function to select records randomly?
It’s easy as someone may already clear on this case when I said on NEWID(). Just use it in ORDER BY clause!
SELECT * FROM Books ORDER BY NEWID()
You got it now. How easily!
Archives
- November 2011
- October 2011
- September 2011
- August 2011
- July 2011
- June 2011
- May 2011
- March 2011
- February 2011
- January 2011
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- January 2010
- December 2009
- October 2009
- August 2009
- July 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- June 2007
Tags
.net 2008 asp.net asp.net mvc asus eee c# corona cpa doctrine dom eee eee pc Internet Marketing ios iPad iphone iPhone development iphone sdk javascript make money netbook online marketing pagerank passion php playstation playstation 3 ps3 ranking ror ruby on rails self help Self Improvement self motivation seo sql success symfony take action the secret ultra compact laptop ultra compact notebook vb.net web development wordpress




