Saturday, September 20, 2008

Fetch random rows through SQL Query

If you need to fetch random rows from a SQL server table and you have an integer column then using RAND() function goes well. However in some cases there is no number column. In such cases how to fetch random rows? SQL Server provides one more mechanism to access random rows:

SELECT TOP <n>
FROM <table>
WHERE <criteria>
ORDER BY NEWID()

The key is the use of NEWID() function that returns a GUID.

As for example:

SELECT TOP 10 * FROM Products ORDER BY NEWID()

Enjoy Programming....




No comments:

back to top