Received: from maia.hub.org (unknown [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id 73EF76339F3 for ; Fri, 10 Jul 2009 08:23:45 -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 47404-10 for ; Fri, 10 Jul 2009 08:23:34 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from ciao.gmane.org (main.gmane.org [80.91.229.2]) by mail.postgresql.org (Postfix) with ESMTP id ED72763246B for ; Fri, 10 Jul 2009 08:23:34 -0300 (ADT) Received: from list by ciao.gmane.org with local (Exim 4.43) id 1MPECR-00030Q-Sa for pgsql-sql@postgresql.org; Fri, 10 Jul 2009 11:23:31 +0000 Received: from 217.110.94.67 ([217.110.94.67]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Fri, 10 Jul 2009 11:23:31 +0000 Received: from spam_eater by 217.110.94.67 with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Fri, 10 Jul 2009 11:23:31 +0000 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-sql@postgresql.org From: Thomas Kellerer Subject: Re: WITH RECURSION output ordering with trees Date: Fri, 10 Jul 2009 13:23:17 +0200 Lines: 59 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: usenet@ger.gmane.org X-Gmane-NNTP-Posting-Host: 217.110.94.67 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.22) Gecko/20090605 Thunderbird/2.0.0.22 Mnenhy/0.7.6.666 In-Reply-To: X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=2.599 tagged_above=0 required=5 tests=RCVD_NUMERIC_HELO=2.599 X-Spam-Level: ** X-Archive-Number: 200907/57 X-Sequence-Number: 32798 Philippe Lang, 10.07.2009 11:10: > Hi, > > I'm playing with the new "WITH RECURSIVE" feature of 8.4. I'm trying to > figure out how to use it with trees. > > Here is the test code I use: > > I'd like to perform a real recursion, and show the tree structure in a > more appopriate way, like this: > > Any idea how to do that? (without trying to sort on the lookup column, > whose values can be random outside this test) The manual has a nice hint on this adding up IDs to "generate" a path like column that can be used for sorting. Try the following: WITH RECURSIVE parse_tree (depth, id, lookup, parent_id, sort_path) AS ( SELECT 0, parent.id, cast(parent.lookup as text), parent.parent_id, array[0] as sort_path FROM recursion_sample parent WHERE parent_id IS NULL UNION ALL SELECT parent.depth + 1, child.id, rpad(' ', depth * 2) || child.lookup, child.parent_id, parent.sort_path || child.id FROM parse_tree parent JOIN recursion_sample child on child.parent_id = parent.id ) select id, lookup from parse_tree order by sort_path ; This will output: id | lookup -----+-------- 1 | a1 2 | b11 243 | c113 645 | c111 823 | c112 6 | b12 583 | c122 845 | c121 9 | b13 10 | c131 (10 rows) Thomas