Re: Selecting a random row - Mailing list pgsql-general

From gnari
Subject Re: Selecting a random row
Date
Msg-id 002301c4c292$3beb32e0$0100000a@wp2000
Whole thread Raw
In response to Selecting a random row  (Kari Lavikka <tuner@bdb.fi>)
Responses Re: Selecting a random row
Re: Selecting a random row
List pgsql-general
From: "Kari Lavikka" <tuner@bdb.fi>
>
> Actually I found an answer. If a I wrap the split point selection to
> subquery then the range of results is from 0 to maximum value (~120k in
> this case)
>
> galleria=> SELECT u.uid FROM users u WHERE u.status = 'a' AND uid >=
> (select cast(cast((SELECT uid FROM users WHERE status = 'a' ORDER BY uid
> DESC LIMIT 1) - 1 AS FLOAT) * random() AS INTEGER)) ORDER BY uid ASC LIMIT
1;
>   uid
> -------
>  91937
> (1 row)

Tthe problem with this is that this is not very random.
If the uids 30000 to 39999 have been missing, but
the uids are more or less contiguous apart from that,
the uid 40000 would be 10000 times more likely to be selected
than average.

Maybe using an OFFSET of (count(*) * random()) and a LIMIT 1
could be practical.

gnari



pgsql-general by date:

Previous
From: Richard Huxton
Date:
Subject: Re: VACUUMING questions...
Next
From: Patrick Hatcher
Date:
Subject: how to edit a function from psql?