SQL – Select Random Records From Table

I found a good article which the author shows you how to select random records from table among different kind of databases.

Here are the example for SQLite, MySQL and PostgreSQL.

SQLite

SELECT Field1, ..., Field2
FROM Table1
ORDER BY Random()
LIMIT 1;

 

MySQL

SELECT Field1, ..., FieldN
FROM Table1
ORDER BY RAND()
LIMIT 1;

 

PostgreSQL

SELECT "Field1", "...", "FieldN"
FROM "Table1"
ORDER BY RANDOM()
LIMIT 1;

 

The number of return records depends on the LIMIT value and you could find other database SQL and the tests details at CarlJ.ca – Selecting Random Records With SQL.

PS: A reply in that article stated that there randomness could not scale well for large table. I don’t have any evidence to support this argument. But for my case, it is already enough. =P
 

Done =)

Reference: CarlJ.ca – Selecting Random Records With SQL

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s