Re: BUG #6607: Strange select behavior - Mailing list pgsql-bugs

From Kevin Grittner
Subject Re: BUG #6607: Strange select behavior
Date
Msg-id 4F95267F020000250004723E@gw.wicourts.gov
Whole thread Raw
In response to BUG #6607: Strange select behavior  (suvisor.root@gmail.com)
Responses Re: BUG #6607: Strange select behavior  (Александр Шепляков<suvisor.root@gmail.com>)
List pgsql-bugs
<suvisor.root@gmail.com> wrote:

> select * from testt where id = (random()* 100000)::integer;
>
> And sometimes it comes out something like this:
> id | val
> -------+--------
> 11894 | 15051
> 29233 | 42198
> 80725 | 90213
> 85688 | 100992
> 88017 | 108075
> (5 rows)
> Here can be 2, 3 or other rows amount in result... But must be
> only one!

No, what you have written will scan the entire table and give each
row a 1 in 100000 chance of being selected.  Maybe something like
this would give you what you want:

select t.* from (select (random()* 100000)::integer) n(r)
  join testt t on (t.id = n.r);

By the way, you might want to tweak that random number before
casting it to int, or you might not get *any* rows back:

test=# select ('0.0000000001'::float * 100000)::int;
 int4
------
    0
(1 row)

Maybe something like:

(select floor(random() * 100000)::int + 1)

-Kevin

pgsql-bugs by date:

Previous
From: Ran Ningyu
Date:
Subject: Re: BUG #6578: Deadlock in libpq after upgrading from 8.4.7 to 8.4.11
Next
From: "Kevin Grittner"
Date:
Subject: Re: BUG #6607: Strange select behavior