Re: sequence number in a result

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Campbell, Lance" <lance(at)illinois(dot)edu>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: sequence number in a result
Date: 2008-10-09 17:14:24
Message-ID: 21127.1223572464@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

"Campbell, Lance" <lance(at)illinois(dot)edu> writes:
> Is there a function or special system label I can use that would
> generate a sequence number in the returning result set?

The usual hack is a temporary sequence:

regression=# create temp sequence s1;
CREATE SEQUENCE
regression=# select nextval('s1'), * from (select * from int8_tbl order by q1) ss;
nextval | q1 | q2
---------+------------------+-------------------
1 | 123 | 456
2 | 123 | 4567890123456789
3 | 4567890123456789 | 123
4 | 4567890123456789 | 4567890123456789
5 | 4567890123456789 | -4567890123456789
(5 rows)

Note that you must use a subselect to ensure that the sequence number
gets stuck on *after* the ORDER BY happens, else what you'll probably
get is numbering corresponding to the unsorted row order.

It would be possible to write a C function to do this with a lot less
overhead than a sequence entails, but no one's got round to it AFAIK.

regards, tom lane

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2008-10-09 17:22:16 Re: trigger parameters, what am I doing wrong ??
Previous Message Relyea, Mike 2008-10-09 17:05:47 Re: sequence number in a result