Received: from magus.postgresql.org (magus.postgresql.org [87.238.57.229]) by mail.postgresql.org (Postfix) with ESMTP id CB8F2152A2F6 for ; Fri, 27 Jul 2012 11:56:39 -0300 (ADT) Received: from mahout.postgresql.org ([98.129.198.123]) by magus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1Sulxw-0001Yb-Lv for pgsql-bugs@postgresql.org; Fri, 27 Jul 2012 14:56:38 +0000 Received: from [204.145.124.246] (helo=wrigleys.postgresql.org) by mahout.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1Sulxi-0002si-U6 for pgsql-bugs@postgresql.org; Fri, 27 Jul 2012 14:56:19 +0000 Received: from www-data by wrigleys.postgresql.org with local (Exim 4.72) (envelope-from ) id 1Sulxi-0003NK-5i for pgsql-bugs@postgresql.org; Fri, 27 Jul 2012 14:56:18 +0000 Date: Fri, 27 Jul 2012 14:56:18 +0000 Message-Id: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Subject: BUG #6774: FOR IN SELECT LOOP ignores ORDER BY To: pgsql-bugs@postgresql.org From: boris@folgmann.de X-Pg-Spam-Score: -1.9 (-) X-Archive-Number: 201207/224 X-Sequence-Number: 33700 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: = 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.