Re: ORDER BY random() LIMIT 1 slowness - Mailing list pgsql-general

From Greg Stark
Subject Re: ORDER BY random() LIMIT 1 slowness
Date
Msg-id 87u1hc4h65.fsf@stark.dyndns.tv
Whole thread Raw
In response to Re: ORDER BY random() LIMIT 1 slowness  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-general
Tom Lane <tgl@sss.pgh.pa.us> writes:

> "Gavin M. Roy" <gmr@justsportsusa.com> writes:
> > SELECT * FROM poetry ORDER BY random() LIMIT 1;
> > [ is slow for 35000 rows ]
>
> Yeah.  Basically this query is implemented as
>   (a) select all 35000 rows of "poetry";
>   (b) compute a random() value for each row;
>   (c) sort by the random() values;
>   (d) take the first row, discard the rest.

If you can generate a random value from your application layer you could do

select * from poetry LIMIT 1 OFFSET <random value>

Can offset values be placeholders in prepared queries? If not then this has
that disadvantage.

--
greg

pgsql-general by date:

Previous
From: Barry Lind
Date:
Subject: Re: JDBC, PgSQL 7.2: transactions not supported!!
Next
From: Medi Montaseri
Date:
Subject: Re: Using Image datatype in Postgres