RSS Feed




More...




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.


Bipin Joshi is a blogger, author and a Kundalini Yogi who writes about apparently unrelated topics - Yoga & technology! A former Software Consultant and trainer by profession, Bipin is programming since 1995 and is working with .NET framework ever since its inception. He is an internationally published author and has authored or co-authored more than half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. Bipin was also a Microsoft MVP for six consecutive years. You can read more about him here.

Stay updated : Twitter  Facebook  Google+



Tags : ADO.NET Data Access SQL Server
Posted On : 23 Jul 2008
Current Rating :
Rate this product :


This page is protected by copyright laws. Copying in any form is strictly prohibited. For Copyright notice and legal terms of use click here.

Protected by Copyscape


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