Re: How to select and result row number?? - Mailing list pgsql-sql

From Ross J. Reedstrom
Subject Re: How to select and result row number??
Date
Msg-id 20020917144635.GB6538@rice.edu
Whole thread Raw
In response to Re: How to select and result row number??  (Bruce Momjian <pgman@candle.pha.pa.us>)
Responses Re: How to select and result row number??  (Tom Lane <tgl@sss.pgh.pa.us>)
Re: How to select and result row number??  (Bruce Momjian <pgman@candle.pha.pa.us>)
List pgsql-sql
On Mon, Sep 16, 2002 at 11:12:06PM -0400, Bruce Momjian wrote:
> Yudie wrote:
<wants numbered records>

> Good question.  The only easy answer I have is the creation of a temp
> table with a SERIAL column:
> 
>     CREATE TEMP TABLE out (cnt SERIAL, other_cols...);
>     INSERT INTO out SELECT ... ORDER BY col;

Hmm, this needs to be:
    INSERT INTO out (ther_cols...) SELECT ... ORDER BY col;

So that the cnt column gets filled from the default.

>     SELECT * FROM out;

On Tue, Sep 17, 2002 at 10:14:58AM -0400, Roland Roberts wrote:
>     create sequence temp_counter;
>     select nextval('temp_counter'), * from whatever;
> 
> If you have an 'order by', the above will not work.  You could then
> try either building a temporary table or using a subselect
> 
>     select nextval('temp_counter'), * from (select .... order by ...);

Approximately the same solution, but without saving the result in a temp
table.

Hmm, with the new dependency code, is the auto-sequence from a SERIAL
in a temp table also a temp sequence? It get's put in the temp schema,
right? Seems we have a workaround for those wanting numbered result
sets.

BTW, Bruce's solution could be useful for those times you want to batch a
potentially large return set, but can't use cursors - the temp table will
live as long as the connection does, so as long as your connection pool
doesn't play round robin games on you, you can use the result count from
the INSERT to calculate batch sizes, and use OFFSET and LIMIT on SELECTs
from the temp table.

Ross


pgsql-sql by date:

Previous
From: "Robert J. Sanford, Jr."
Date:
Subject: Join Question
Next
From: Tom Lane
Date:
Subject: Re: How to select and result row number??