Re: How ad an increasing index to a query result?

From: Merlin Moncure <mmoncure(at)gmail(dot)com>
To: rod(at)iol(dot)ie
Cc: Alban Hertroys <dalroi(at)solfertje(dot)student(dot)utwente(dot)nl>, Josip <josip(dot)2000(at)gmail(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: How ad an increasing index to a query result?
Date: 2009-10-20 01:39:51
Message-ID: b42b73150910191839nb37001cp1ea4d4af9c21b25@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Sun, Oct 18, 2009 at 12:00 PM, Raymond O'Donnell <rod(at)iol(dot)ie> wrote:
> On 18/10/2009 11:30, Alban Hertroys wrote:
>
>> Short of enumerating those results in your application, the easiest
>> approach is probably to wrap your query in a join with generate_series
>> like so:
>>
>> SELECT a, s.b
>> FROM (
>>     SELECT a
>>     FROM table1
>>     ORDER BY a DESC LIMIT 5
>> ) AS t1, generate_series(5, 1, -1) AS s(b)
>>
>
> Won't that just give you the cartesian product of the two sets? I tried
> something similar yesterday out of curiosity, and that's what I got.
>
> The only things I can think of are (i) as you say, enumerate the results
> in the application or (ii) use a temporary sequence as someone else
> suggested.

yeah, the above gives a cartesian product. Row number is really the
way to go here. Using pre window tactics, it looks like we need:

select a, b from
(
select a, nextval('c') as b from
(
SELECT a,
FROM table1
ORDER BY a DESC LIMIT 5
) q order by a
) q order by a desc;

aside: it's never a good idea to write queries like this:
select func(), foo from bar order by foo limit x;
if you are concerned about how many times foo executes. This is a
huge gotcha that constantly comes up on the lists. see the warning
here:

http://www.postgresql.org/docs/8.3/interactive/explicit-locking.html#ADVISORY-LOCKS

merlin

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Merlin Moncure 2009-10-20 02:21:26 Re: When much of a DB is large objects - PG 8.4
Previous Message David Wall 2009-10-20 01:11:14 When much of a DB is large objects - PG 8.4