SQL SERVER – Retrieving Random Rows from Table Using NEWID()
Posted
by pinaldave
on SQL Authority
See other posts from SQL Authority
or by pinaldave
Published on Fri, 16 Nov 2012 01:30:44 +0000
Indexed on
2012/11/16
5:04 UTC
Read the original article
Hit count: 319
PostADay
|sql
|SQL Authority
|SQL Function
|SQL Query
|SQL Server
|SQL Tips and Tricks
|T SQL
|Technology
I have previously written about how to get random rows from SQL Server.
- SQL SERVER – Generate A Single Random Number for Range of Rows of Any Table – Very interesting Question from Reader
- SQL SERVER – Random Number Generator Script – SQL Query
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
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.
Reference: Pinal Dave (http://blog.sqlauthority.com)
Filed under: PostADay, SQL, SQL Authority, SQL Function, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology
© SQL Authority or respective owner