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.
About The Author
Madhivanan,an MSc computer Science graduate from Chennai-India, works as a works as a Lead Subject Matter Expert at a company that simplifies BIG data. He started his career as a developer working with Visual Basic 6.0, SQL Server 2000 and Crystal Report 8. As years went by, he started working more on writing queries in SQL Server. He now has good level of knowledge in SQLServer, Oracle, MySQL and PostgreSQL as well. He is also one of the leading posters at www.sqlteam.com and a moderator at www.sql-server-performance.com. His T-sql blog is at http://beyondrelational.com/blogs/madhivanan
5 comments:
I am not able to follow what is difference in Method1 and 2. Can you explain in detail
Run the queries and see the difference
Its interesting that you use sysobjects here although I am not sure why. Can't I just say?
SELECT 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?
Manjot: Check this post to see if it helps
SQL Server Books You Must Have In Your Collection
Post a Comment