Re: enumerating rows

From: "Oliver Elphick" <olly(at)lfix(dot)co(dot)uk>
To: Kovacs Zoltan <kovacsz(at)pc10(dot)radnoti-szeged(dot)sulinet(dot)hu>
Cc: "Koen Antonissen" <Koen(at)Cee-Kay(dot)net>, pgsql-sql(at)postgresql(dot)org
Subject: Re: enumerating rows
Date: 2001-04-11 16:46:22
Message-ID: 200104111646.f3BGkM205840@linda.lfix.co.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Kovacs Zoltan wrote:
>> Use the "serial" column type.
>Unfortunately it's not what I expect. Assume that I have an arbitrary
>"SELECT expr1 as column1, expr2 as column2, ..." which gives
>
>column1 | column2 | ...
>--------+---------+- ...
>......data..............
>........................
>
>I would like to get the same result with the only plus column row_no:
>
>row_no | column1 | column2 | ...
>-------+---------+---------+- ...
> 1 | ......data..............
> 2 | ........................
>.................................
>
>with a new SELECT statement: "SELECT ?????, expr1 as column1, expr2 as
>column2, ...". What to write instead of ??????

Here is a method which is fairly cumbersome, but will do what you want.
(Whether what you want is useful, is another matter. The row numbers
have no meaning except to delineate which row is printed after which; they
bear no relation to their order in the table.)

Create the C code shown in the attachment.

Compile it (the example shown is for Linux, see the programmer's manual for
how to do it on other systems):

gcc -fpic -c rowno.c
gcc -shared -o rowno.so rowno.o

In the database, create functions as shown (remember to change
the directory from /tmp!):

CREATE FUNCTION reset_row() RETURNS int4
AS '/tmp/rowno.so' LANGUAGE 'C';

CREATE FUNCTION row_no() RETURNS int4
AS '/tmp/rowno.so' LANGUAGE 'C';

Now you can use the function:

bray=# select row_no() as row,id,name from person;
row | id | name
------+--------+-------------------------------------------------------
1 | 100001 | Mr Graham Love (Director)
2 | 100002 | AILEEN BROWN
...

but you have to do this in between queries:

bray=# select reset_row();

because the numbers don't reset themselves:

bray=# select row_no() as row,id,name from person;
row | id | name
-------+--------+-------------------------------------------------------
6015 | 100001 | Mr Graham Love (Director)
6016 | 100002 | AILEEN BROWN
...

Attachment Content-Type Size
rowno.c text/x-csrc 236 bytes

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Gerald Gutierrez 2001-04-11 17:58:42 Making SELECT COUNT(seed) FROM fast
Previous Message Kovacs Zoltan 2001-04-11 16:43:35 Re: enumerating rows