SQL SERVER – Retrieving Random Rows from Table Using NEWID()

I have previously written about how to get random rows from SQL Server. Here is a new trick to get random rows from table data with NEWID().

However, I have not blogged about following trick before. Let me share the trick here as well. You can generate random scripts using following methods as well.

USE AdventureWorks2012
GO
-- Method 1
SELECT TOP 100 *
FROM Sales.SalesOrderDetail
ORDER BY NEWID()
GO
-- Method 2
SELECT TOP 100 *
FROM Sales.SalesOrderDetail
ORDER BY CHECKSUM(NEWID())
GO

Table and toolbar.

You will notice that using NEWID() in the ORDER BY will return random rows in the result set. How many of you knew this trick? You can run above script multiple times and it will give random rows every single time.

Watch a 60 second video on this subject

Note: This method can be very resource intensive for large resultsets.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.

SQL Function
Previous Post
Storing UTC and Local Time Side by Side
Next Post
Restoring a TDE Protected Database on Another Server

Related Posts

24 Comments. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.