Re: selecting random row - Mailing list pgsql-general

From Holger Klawitter
Subject Re: selecting random row
Date
Msg-id 3CA967D2.12D0D8DE@klawitter.de
Whole thread Raw
In response to selecting random row  (Heiko Klein <Heiko.Klein@met.no>)
List pgsql-general
Hi,

> Right now (in perl), I select the complete list of id's into a @list, do
> a $id = $list[rand(@list)] and have the right row. But this seems to be
> very time-consuming, and I would like to have it done completely in the
> Pg-database.

You can order by random and get the first row:

select
    id
from
    table
where
    agr>=60 and sex = 'm'
order by
    random()
limit
    1
;

This will also compute the whole result set - well, you have to in order
to get the value set to select from - but at least you don't have to
pull all data into your application tier.

With kind regards / Mit freundlichem Gruß
    Holger Klawitter
--
Holger Klawitter
holger@klawitter.de                             http://www.klawitter.de

pgsql-general by date:

Previous
From: Daniel Lundin
Date:
Subject: Re: selecting random row
Next
From: Mark kirkwood
Date:
Subject: Re: Re : Solaris Performance - Profiling