Re: Problem with ORDER BY and random() ?

From: "scott(dot)marlowe" <scott(dot)marlowe(at)ihs(dot)com>
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:24:12
Message-ID: Pine.LNX.4.33.0309231621190.12858-100000@css120.ihs.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Tue, 23 Sep 2003 Jean-Francois(dot)Doyon(at)ccrs(dot)nrcan(dot)gc(dot)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" ...

Of course not, they're already sorted randomly. i.e. random() assigns a
value between 0 and 1 like so:

select random(),aid from accounts limit 10;
random | aid
--------------------+-----
0.416937615450908 | 1
0.398205195273368 | 2
0.40122325271425 | 3
0.68575628226891 | 4
0.0215648445401177 | 5
0.0346587472756667 | 6
0.906103603498127 | 7
0.347187338558579 | 8
0.833244230986221 | 9
0.786484897968585 | 10

So, if we make a subselect, we get:

select * from (select random() as r,aid from accounts limit 10) as a
order by a.r;
r | aid
--------------------+-----
0.0806112047660217 | 8
0.0979125742325152 | 4
0.206458460170058 | 9
0.492886080170463 | 5
0.535966586571171 | 6
0.553715904501135 | 2
0.631926567122306 | 7
0.761918006353973 | 10
0.902183785523374 | 3
0.978199429334234 | 1

We can see what number we were ordering by. Since the chances of having
two random numbers be the same float is pretty close to zero, the order by
random(),id will never get to the id, because random() has no repeating
values.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2003-09-23 22:30:36 Re: Problem with ORDER BY and random() ?
Previous Message Christopher Browne 2003-09-23 22:17:04 Re: Problem with ORDER BY and random() ?