Wednesday 20 July 2011

SQL: Get random records from database

Question:
How to get a number of random records from a table.


Answer:
That depends on your database.
The main idea is to add a virtual new column in your table query and to attribute a random value to this column.
Then you limit the result set to the number of records you want.

Example for SQL server that returns 3 random records
-- NEWID() returns a random GUID
SELECT TOP 3 * FROM myTable
ORDER BY NEWID()


The same example in MySql
-- RAND() returns a random number
SELECT * FROM myTable
ORDER BY RAND()
LIMIT 3


Get random records in PostgreSQL
-- RANDOM() returns a random number
SELECT * FROM myTable
ORDER BY RANDOM()
LIMIT 3



No comments: