Received: from maia.hub.org (unknown [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id 0F5A76338B9 for ; Mon, 6 Jul 2009 22:44:54 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 71746-02 for ; Mon, 6 Jul 2009 22:44:51 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from ns1.officenet.no (unknown [195.159.87.244]) by mail.postgresql.org (Postfix) with ESMTP id 70ED463370B for ; Mon, 6 Jul 2009 22:44:51 -0300 (ADT) Received: from [192.168.2.102] (helo=andreak-laptop.localnet) by ns1.officenet.no with esmtpsa (TLS-1.0:DHE_RSA_AES_256_CBC_SHA1:32) (Exim 4.69) (envelope-from ) id 1MNzje-0006xI-8Z for pgsql-sql@postgresql.org; Tue, 07 Jul 2009 03:44:48 +0200 From: Andreas Joseph Krogh Organization: OfficeNet AS To: pgsql-sql@postgresql.org Subject: Order of "WITH RECURSIVE" output Date: Tue, 7 Jul 2009 03:44:35 +0200 User-Agent: KMail/1.12.0 (Linux/2.6.28-13-generic; KDE/4.2.95; i686; ; ) MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <200907070344.36084.andreak@officenet.no> X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0.1 tagged_above=0 required=5 tests=RDNS_NONE=0.1 X-Spam-Level: X-Archive-Number: 200907/18 X-Sequence-Number: 32759 Hi all. Take this example from src/test/regress/sql/with.sql: WITH RECURSIVE subdepartment(level, id, parent_department, name) AS ( -- non recursive term SELECT 1, * FROM department WHERE name =3D 'A' UNION ALL -- recursive term SELECT sd.level + 1, d.* FROM department AS d, subdepartment AS sd WHERE d.parent_department =3D sd.id ) SELECT * FROM subdepartment ORDER BY name; level | id | parent_department | name =2D------+----+-------------------+------ 1 | 1 | 0 | A 2 | 2 | 1 | B 3 | 3 | 2 | C 3 | 4 | 2 | D 4 | 6 | 4 | F (5 rows) If I omit "ORDER BY", is the output *guaranteed* (according to some standar= d) to be ordered in "hierarchy"-order, meaning each parent-department is al= ways output before its respective child, or do I have to calculate a "level= " column (like in the example above) and specify "ORDER BY LEVEL" to be 100= %? I'm using WITH RECURSIVE as sub-queries to build up arrays of parents in ea= ch output-row and would like as little overhead as possible and hence avoid= unnecessary sorting. =2D-=20 Andreas Joseph Krogh Senior Software Developer / CTO =2D-----------------------+---------------------------------------------+ OfficeNet AS | The most difficult thing in the world is to | Rosenholmveien 25 | know how to do a thing and to watch | 1414 Troll=C3=A5sen | somebody else doing it wrong, without | NORWAY | comment. | | | Tlf: +47 24 15 38 90 | | =46ax: +47 24 15 38 91 | | Mobile: +47 909 56 963 | | =2D-----------------------+---------------------------------------------+