Re: rownum - Mailing list pgsql-sql

From Tom Lane
Subject Re: rownum
Date
Msg-id 4353.1045200034@sss.pgh.pa.us
Whole thread Raw
In response to Re: rownum  (Josh Berkus <josh@agliodbs.com>)
Responses Re: rownum
List pgsql-sql
Josh Berkus <josh@agliodbs.com> writes:
>> sorry about this - braindead and cannot find in doc.  what's pg's
>> rownum pseudo-column or function name that returns the record number of
>> a set?

> There isn't one, unless there's something in /contrib that you can build.

Right now the only way I've heard of is to use a sequence, for example
create temp sequence rownum;
select nextval('rownum'), ... from ...;
drop sequence rownum;

This is a hack, and it will fail if the SELECT involves any sort
specification (not only ORDER BY, but DISTINCT) because the nextval()s
will be computed before sorting.  You can get around that with
select nextval('rownum'), * from (select ... order by ...) sub;

The overhead of using a sequence for this is pretty annoying.  It would
be a simple matter to write a C function that emits sequential values
without any database access (see pg_stat_get_backend_idset() for some
inspiration).  But you'd still need the subselect to avoid getting
re-sorted.  AFAICS any rownum() function that doesn't behave like that
is a flat violation of the SQL standard...
        regards, tom lane


pgsql-sql by date:

Previous
From: Stephan Szabo
Date:
Subject: Re: Passing arrays
Next
From: "Wei Weng"
Date:
Subject: Re: Extending Datatype