Select Random Rows from a Table – SQL Server

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

image

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()

image

The second method is easy to use and fetches data more randomly.

5 comments:

  1. I am not able to follow what is difference in Method1 and 2. Can you explain in detail

    ReplyDelete
  2. Run the queries and see the difference

    ReplyDelete
  3. 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()

    ReplyDelete
  4. great blog and good query. I am looking for a t-sql book to learn how to write queries. any suggestion?

    ReplyDelete