BUG #6774: FOR IN SELECT LOOP ignores ORDER BY - Mailing list pgsql-bugs

From boris@folgmann.de
Subject BUG #6774: FOR IN SELECT LOOP ignores ORDER BY
Date
Msg-id E1Sulxi-0003NK-5i@wrigleys.postgresql.org
Whole thread Raw
Responses Re: BUG #6774: FOR IN SELECT LOOP ignores ORDER BY  (hubert depesz lubaczewski <depesz@depesz.com>)
List pgsql-bugs
The following bug has been logged on the website:

Bug reference:      6774
Logged by:          Boris Folgmann
Email address:      boris@folgmann.de
PostgreSQL version: 8.4.12
Operating system:   CentOS 6.3
Description:=20=20=20=20=20=20=20=20

This is an really interesting one!
I've trimmed down the problem so you can simply reproduce it by copy &
paste:

CREATE OR REPLACE FUNCTION ignores_order_by()
RETURNS TABLE(datname VARCHAR) AS $$
DECLARE
        r       RECORD;
BEGIN
        FOR r IN SELECT * FROM pg_database WHERE datallowconn ORDER BY
datname
        LOOP
            datname :=3D r.datname;
            RETURN NEXT;
        END LOOP;
END;
$$ LANGUAGE 'plpgsql';

CREATE OR REPLACE FUNCTION respects_order_by()
RETURNS TABLE(dn VARCHAR) AS $$
DECLARE
        r       RECORD;
BEGIN
        FOR r IN SELECT * FROM pg_database WHERE datallowconn ORDER BY
datname
        LOOP
            dn :=3D r.datname;
            RETURN NEXT;
        END LOOP;
END;
$$ LANGUAGE 'plpgsql';

SELECT * from ignores_order_by();
SELECT * from respects_order_by();

Now compare the different output!
The only difference of the two functions is that the first one uses a
variable with the same name of a column.
This might be a feature and not a bug, but browsing through the
documentation I could not find any documented restrictions on variable names
in this context.

pgsql-bugs by date:

Previous
From: Jez Wain
Date:
Subject: Re: BUG #6760: make check fails on strings SQL T581 regex test
Next
From: hubert depesz lubaczewski
Date:
Subject: Re: BUG #6774: FOR IN SELECT LOOP ignores ORDER BY