X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (av.hub.org [200.46.204.144]) by postgresql.org (Postfix) with ESMTP id 5EB5E11F7D94 for ; Mon, 10 Apr 2006 12:17:39 -0300 (ADT) X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Score: 0.55 X-Spam-Level: X-Spam-Status: No, score=0.55 required=5 tests=[NO_REAL_NAME=0.55] Received: from postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id m7VEDNY4nQ+J for ; Mon, 10 Apr 2006 12:17:18 -0300 (ADT) X-Greylist: delayed 00:07:08.182878 by SQLgrey- Received: from lon1-mail-1.visp.demon.net (lon1-mail-1.visp.demon.net [193.195.70.4]) by postgresql.org (Postfix) with ESMTP id 86B4311F7CE8 for ; Mon, 10 Apr 2006 12:17:09 -0300 (ADT) Received: from xphome (host-70a-en-u-181.dial.beeb.net [62.56.2.181] (may be forged)) by lon1-mail-1.visp.demon.net (MOS 3.5.8-GR) with ESMTP id DWO66622; Mon, 10 Apr 2006 16:09:58 +0100 (BST) Reply-To: From: To: Subject: how to use recursion to find end nodes of a tree Date: Mon, 10 Apr 2006 16:09:57 +0100 Message-ID: <000201c65cb0$d8a6fe20$0100a8c0@xphome> MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit X-Priority: 3 (Normal) X-MSMail-Priority: Normal X-Mailer: Microsoft Outlook, Build 10.0.6626 Importance: Normal X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.2180 X-Archive-Number: 200604/62 X-Sequence-Number: 24871 Hello All, I have been having a really hard time trying to come up with a pl/pgsql recursive function to returns the end nodes of a tree. Here is an example table definition: CREATE TABLE parent_child ( parent_id integer NOT NULL, child_id integer NOT NULL ); INSERT INTO parent_child (parent_id, child_id) VALUES (1, 2); INSERT INTO parent_child (parent_id, child_id) VALUES (1, 3); INSERT INTO parent_child (parent_id, child_id) VALUES (1, 4); INSERT INTO parent_child (parent_id, child_id) VALUES (2, 5); INSERT INTO parent_child (parent_id, child_id) VALUES (2, 6); INSERT INTO parent_child (parent_id, child_id) VALUES (4, 7); INSERT INTO parent_child (parent_id, child_id) VALUES (4, 8); INSERT INTO parent_child (parent_id, child_id) VALUES (4, 9); INSERT INTO parent_child (parent_id, child_id) VALUES (9, 10); This produces the following tree of data: 1 ___|___ | | | 2 3 4 _|_ _|_ | | | | | 5 6 7 8 9 | 10 I want to create a function that returns the terminating nodes of of this tree below a certain level i.e. if I input 1 to the function I need it to return 5,6,3,7,8,10. If I input 4 to the function I would get 7,8,10. I have written recursive functions which return all nodes on a branch of a tree but I can't think of a way to return the end nodes does anyone know of a solution? Many thanks, Mike