Order of "WITH RECURSIVE" output

From: Andreas Joseph Krogh <andreak(at)officenet(dot)no>
To: pgsql-sql(at)postgresql(dot)org
Subject: Order of "WITH RECURSIVE" output
Date: 2009-07-07 01:44:35
Message-ID: 200907070344.36084.andreak@officenet.no
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

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 = 'A'

UNION ALL

-- recursive term
SELECT sd.level + 1, d.* FROM department AS d, subdepartment AS sd
WHERE d.parent_department = sd.id
)
SELECT * FROM subdepartment ORDER BY name;

level | id | parent_department | name
-------+----+-------------------+------
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 standard) to be ordered in "hierarchy"-order, meaning each parent-department is always 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 each output-row and would like as little overhead as possible and hence avoid unnecessary sorting.

--
Andreas Joseph Krogh <andreak(at)officenet(dot)no>
Senior Software Developer / CTO
------------------------+---------------------------------------------+
OfficeNet AS | The most difficult thing in the world is to |
Rosenholmveien 25 | know how to do a thing and to watch |
1414 Trollåsen | somebody else doing it wrong, without |
NORWAY | comment. |
| |
Tlf: +47 24 15 38 90 | |
Fax: +47 24 15 38 91 | |
Mobile: +47 909 56 963 | |
------------------------+---------------------------------------------+

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2009-07-07 01:55:35 Re: Order of "WITH RECURSIVE" output
Previous Message Peter Headland 2009-07-07 01:22:50 Best way to simulate Booleans