Thursday, March 12, 2009

Randomize Records in a Database Table (PostgreSQL)

Context:
Suppose you have a bunch of records stored in a database table. However, for whatever reason, you may want to have a randomized version of the table. Alternatively, you may want to return a random record that match a query. Here's what you can do.

PostgreSQL Solution:
(1) Randomized version of the table
CREATE TABLE new_randomized_table AS
SELECT * FROM original_table ORDER BY random();

(2) Return random record from a given query
SELECT * FROM original_table WHERE id = 1 ORDER BY random() LIMIT 1;

You can find solutions for other database servers at this site: http://www.carlj.ca/2007/12/16/selecting-random-records-with-sql/

No comments:

Post a Comment