Learn ASP.NET Core 2 and Angular 6 in October 2018. Instructor-led online courses by Bipin Joshi. Read more...
Instructor-led Online Courses by Bipin Joshi : ASP.NET Core | Angular | Design Patterns
Registration open for October 2018 batches. Read more here.

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 software consultant, trainer, author and spiritual yoga mentor having 23+ years of experience in software development. He teaches private online courses in ASP.NET Core and Angular to individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

He will be teaching ASP.NET Core 2.1 and Angular 6.1 in October 2018. Click here for his online course schedule and more details.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 23 July 2008


Tags : ADO.NET Data Access SQL Server