Re: Problem with ORDER BY and random() ? - Mailing list pgsql-general

From Stephan Szabo
Subject Re: Problem with ORDER BY and random() ?
Date
Msg-id 20030923152002.K38229@megazone.bigpanda.com
Whole thread Raw
In response to Problem with ORDER BY and random() ?  (Jean-Francois.Doyon@CCRS.NRCan.gc.ca)
List pgsql-general
On Tue, 23 Sep 2003 Jean-Francois.Doyon@CCRS.NRCan.gc.ca wrote:

> Hello,
>
> I'm trying to retrieve a limited number of random rows, and order them by a
> column, and am not having any luck with that last part:
>
> SELECT * FROM tablename ORDER BY random(), id LIMIT 10
>
> Returns everything more or less as expected, except for the fact that the
> results aren't sorted by "id" ...

The above basically says sort by random() and then for equal values of
that sort those by id.  That's not going to sort by id really except in
cases that random() gave the same value. You probably wanted something
with a subselect that did the limiting with the order by on the outside,
like:
SELECT * from (SELECT * FROM tablename ORDER BY random() LIMIT 10) as foo
ORDER BY id;

However, this is a fairly expensive way to generate random rows for a big
table.  The archives should have some better mechanisms in them.

pgsql-general by date:

Previous
From: Tom Lane
Date:
Subject: Re: Problem with ORDER BY and random() ?
Next
From: Mike Mascari
Date:
Subject: Re: Problem with ORDER BY and random() ?