RSS Feed
RSS Feed
Search
AddThis Feed Button
Bookmark and Share





Fetching Random Rows From SQL Se

Tip: Fetching Random Rows From SQL Server

Recently I needed to fetch random rows from a SQL server table. If you have an integer column then using RAND() function goes well. However in my case there was no number column. In such cases you can use the following query:

SELECT TOP <n> <column list> 
FROM <table> 
WHERE <criteria> 
ORDER BY NEWID()

The key is the use of NEWID() function that returns a GUID. An example query would look something like this:

SELECT TOP 10 * 
FROM Employees
ORDER BY NEWID()

This way is also useful for selecting data for testing purposes.




Posted On : 23 Jul 2008
Current Rating :
Rate This Article :

About the Author
Bipin Joshi
Bipin Joshi is a blogger and writes about Yoga, spirituality and technology. A former Software Consultant by profession he worked for many years with Microsoft technologies such as C, C++, C#, VB, ASP and ASP.NET. Bipin got selected as a Most Valuable Professional (MVP) by Microsoft for six consecutive years before he decided to take a back seat from the mainstream IT to continue his spiritual interests. More details about him can be read here.



Copyright (C) bipinjoshi.net. All rights reserved.
Contact Us
Read Terms Of Use
Hosted By DiscountASP