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

From Christopher Browne
Subject Re: Problem with ORDER BY and random() ?
Date
Msg-id m3u173ywtb.fsf@wolfe.cbbrowne.com
Whole thread Raw
In response to Problem with ORDER BY and random() ?  (Jean-Francois.Doyon@CCRS.NRCan.gc.ca)
List pgsql-general
Centuries ago, Nostradamus foresaw when Jean-Francois.Doyon@CCRS.NRCan.gc.ca would write:
> 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" ...

I'm not sure why you are surprised at this.  You asked to order them
primarily by random(), and then by id, if the random values were
equal, and that is clearly the order that you are getting.

If you want to order the 10 records by id, you might accomplish that
by the following:

  select * from (select * from tablename order by random() limit 10)
     order by id;
--
let name="cbbrowne" and tld="cbbrowne.com" in name ^ "@" ^ tld;;
http://www3.sympatico.ca/cbbrowne/finances.html
Rules of the Evil Overlord  #62. "I will design fortress hallways with
no alcoves or protruding structural supports which intruders could use
for cover in a firefight." <http://www.eviloverlord.com/>

pgsql-general by date:

Previous
From: Christopher Browne
Date:
Subject: Re: About GPL and proprietary software
Next
From: "Marten G Mickos"
Date:
Subject: Re: About GPL and proprietary software