Re: Enumerating a row set

From: Steve Atkins <steve(at)blighty(dot)com>
To: pgsql-general List <pgsql-general(at)postgresql(dot)org>
Subject: Re: Enumerating a row set
Date: 2009-03-26 22:56:50
Message-ID: 686194A2-379D-4A23-8668-54706D16F376@blighty.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


On Mar 26, 2009, at 3:42 PM, George Sakkis wrote:

> Hi all,
>
> Is there a function similiar to Python's enumerate() [1] ? Searching
> the docs didn't reveal any relevant builtin but I hope it's doable in
> pgsql. Ideally I'd like a function that can be used as:
>
> SELECT e.i, e.col1, e.col2
> FROM enumerate(some_table, 'i') e
> LIMIT 10
>
> i col1 col2
> =========
> 0 ... ...
> 1 ... ...
> ... ... ...
> 9 ... ...
>
> Also ideally it should work on any rowset (e.g. nested select), not
> just on concrete tables.

You're looking for what's called rownum in some other databases.

You can do it in postgresql with a temporary sequence, sometimes at
least:

abacus=# create temporary sequence bar;
CREATE SEQUENCE

abacus=# select setval('bar', 1, false);
setval
--------
1
(1 row)

abacus=# select nextval('bar'), baz from foo;
nextval | baz
---------+--------
1 | red
2 | yellow
3 | blue

Cheers,
Steve

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Scott Marlowe 2009-03-26 23:10:15 Re: Is there a meaningful benchmark?
Previous Message Dhaval Jaiswal 2009-03-26 22:49:59 Re: how to avoid that a postgres session eats up all the memory