Re: ORDER BY random() LIMIT 1 slowness

From: Greg Stark <gsstark(at)mit(dot)edu>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: "Gavin M(dot) Roy" <gmr(at)justsportsusa(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: ORDER BY random() LIMIT 1 slowness
Date: 2002-12-17 18:46:42
Message-ID: 87u1hc4h65.fsf@stark.dyndns.tv
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> writes:

> "Gavin M. Roy" <gmr(at)justsportsusa(dot)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

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Medi Montaseri 2002-12-17 19:12:19 Re: Using Image datatype in Postgres
Previous Message Barry Lind 2002-12-17 17:43:49 Re: JDBC, PgSQL 7.2: transactions not supported!!