Re: Problem with ORDER BY and random() ?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Jean-Francois(dot)Doyon(at)CCRS(dot)NRCan(dot)gc(dot)ca
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Problem with ORDER BY and random() ?
Date: 2003-09-23 22:30:36
Message-ID: 24031.1064356236@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Jean-Francois(dot)Doyon(at)CCRS(dot)NRCan(dot)gc(dot)ca writes:
> 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" ...

Well, no. You specified random() as the major sort key. Only rows that
happened to have equal random() values would be sorted by id.

This would work:

SELECT * FROM
(SELECT * FROM tablename ORDER BY random() LIMIT 10) as ss
ORDER BY id;

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Dennis Gearon 2003-09-23 22:31:08 Re: Problem with ORDER BY and random() ?
Previous Message scott.marlowe 2003-09-23 22:24:12 Re: Problem with ORDER BY and random() ?