Info

You are currently browsing the The Rhodium Toad weblog archives for March, 2009.

Calendar
March 2009
M T W T F S S
« Feb    
 1
2345678
9101112131415
16171819202122
23242526272829
3031  
Categories
Links

Archive for March 2009

Selecting random rows from a table

The question of how to select some random items from a table is one that comes up fairly often in the IRC channel (and as the subject of blog posts, such as this one from depesz).
While there is a simple solution of this form (let’s assume for now that we want to select 5 uniformly random rows from table “items”):

select * from items order by random() limit 5;

this is unfortunately slow if the table has more than a small number of rows. It is possible to do far better, though there aren’t really any perfect solutions that don’t resort to procedural logic in some way. Let’s start by looking at how to do better in plain SQL.
Read the rest of this entry »

|