Monday, January 14, 2013

How to select a random row from a SQL database table

Here is how to select a random row with MySQL:
SELECT column FROM table
ORDER BY RAND()
LIMIT 1
For PostgreSQL, change =RAND()= to =RANDOM()=.

For Microsoft SQL Server:
SELECT TOP 1 column FROM table
ORDER BY NEWID()
Remove =LIMIT 1= (=TOP 1=) to return all rows from a table in a random order.

No comments:

Post a Comment