Tuesday, February 21, 2012

returning limited number of records!

I am using ORDER BY NEWID() to return random record from sql database. how do i go about returning only 5 random records instead of all records.

Thanks.Since SELECT * FROM Table ORDER BY NEWID() will return the rows in a random order, all you need to do is use the TOP keyword to limit the results for that particular query.

SELECT TOP 5 * FROM Table
ORDER BY NEWID()

If, for some reason, that doesn't work, there's the slightly less elegant solution of

SET ROWCOUNT = 5
SELECT * FROM Table
ORDER BY NEWID()
SET ROWCOUNT = 0

I hope this helps.|||it's working perfect.

thanks.

No comments:

Post a Comment