April 13, 2011 at 11:54 pm
Hi All,
Few days back, one of my colleague asked me how to get 5 arbitrary different rows from a table which is consisting of multiple rows ?
Since SQL Server 2008 has NewId() function so i replied him you can use following script for your table
Select top 5 * from TableName
order by NewId();
I want to know - are there some other ways to know arbitrary rows from any database table ?
April 14, 2011 at 12:26 am
You can use RAND() function to get the result
SELECT TOP 5
columnname,
*
FROM tablename
ORDER BY Rand()
April 14, 2011 at 12:46 am
I guess this will return the same set of records every time...
April 14, 2011 at 2:00 am
srikant maurya (4/14/2011)
You can use RAND() function to get the resultSELECT TOP 5
columnname,
*
FROM tablename
ORDER BY Rand()
That's equivalent to ORDER BY 'A constant value'. Rand returns the same value for all rows of a resultset.
You can use TableSample, along with TOP. That'll be semi-random, likely to be faster than the order by NewID, but it's rows off a random page, not truly random rows.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply