row_number() for Postgres before 8.4

Unfortunately i found a solution for this problem only this week, after the new postgres version 8.4 was already released. In the new version this function is already implemented along with many other functions called “window functions“.
In any way, for everyone that still uses Postgress version less then 8.4, here is my solution for this -


CREATE OR REPLACE FUNCTION counter(int) RETURNS INT AS $$
return $_[0] + $_SHARED{counter}++; $$
LANGUAGE plperl;

CREATE OR REPLACE FUNCTION get_counter() RETURNS INT AS $$
return $_SHARED{counter}++;
$$
immutable
LANGUAGE plperl;

create or replace function get_row_number() returns integer as
’select counter(get_counter()*-1);’
language sql

After declaring this set of functions you will be able to run queries like this -

select get_row_number(),* from table...

I think this solution is better then creating temporary sequences and using nextval(’rownum’).

Your comments are appreciated

No Comments yet »

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security text shown in the picture. Click here to regenerate some new text.
Click to hear an audio file of the anti-spam word