Tuesday, December 29, 2009

Generate random rows with SQL

The secret to retrieve random rows from database is really simple. Here are some example SQL statements that do not require additional application logic.

SQL Server:
SELECT TOP 1 *
FROM Users
ORDER BY NEWID()

MySQL:
SELECT * FROM Users
ORDER BY RAND()
LIMIT
1;

Oracle:
SELECT * FROM
(SELECT * FROM Users
ORDER BY dbms_random.value )
WHERE rownum = 1

PostgreSQL:
SELECT * FROM Users
ORDER BY RANDOM()
LIMIT
1

Access:
SELECT TOP 1 *
FROM Users
ORDER BY Rnd(UserID)


Cheers!
 

Get paid for your opinions! Click on the banner above to join Planet Pulse. Its totally free to sign up, and you can earn UNLIMITED. Find out more by visiting PLANET PULSE.
Sign up for PayPal and start accepting credit card payments instantly. http://www.emailcashpro.com
July Code Blog Copyright © 2010 Blogger Template Designed by Bie Blogger Template