There are multiple ways to randomly select rows from a table. In this blog post, I will show two ways of doing so:
Method 1: Random Number of Rows
DECLARE @n int
SET @n=RAND()*10
SELECT TOP (@n) * FROM sysobjects
Method 2: Random Number of Rows as well as Data
DECLARE @n int
SET @n=RAND()*10
SELECT TOP (@n) * FROM sysobjects
ORDER BY NEWID()
The second method is easy to use and fetches data more randomly.
I am not able to follow what is difference in Method1 and 2. Can you explain in detail
ReplyDeleteRun the queries and see the difference
ReplyDeleteIts interesting that you use sysobjects here although I am not sure why. Can't I just say?
ReplyDeleteSELECT top 10 percent * from [tablenaame] order by newid()
great blog and good query. I am looking for a t-sql book to learn how to write queries. any suggestion?
ReplyDeleteManjot: Check this post to see if it helps
ReplyDeleteSQL Server Books You Must Have In Your Collection