Received: from mail.postgresql.org (webmail.postgresql.org [216.126.85.28]) by mail.postgresql.org (8.11.1/8.11.1) with SMTP id eBU2XsL62494 for ; Fri, 29 Dec 2000 21:33:54 -0500 (EST) (envelope-from pgsql-sql-owner@postgresql.org) Received: from news.tht.net (news.hub.org [216.126.91.242]) by mail.postgresql.org (8.11.1/8.11.1) with ESMTP id eBSEc0L10181 for ; Thu, 28 Dec 2000 09:38:00 -0500 (EST) (envelope-from news@news.tht.net) Received: (from news@localhost) by news.tht.net (8.9.3/8.9.3) id JAA78698 for pgsql-sql@postgresql.org; Thu, 28 Dec 2000 09:26:22 -0500 (EST) (envelope-from news) X-Authentication-Warning: news.tht.net: news set sender to using -f From: Ron Peterson X-Newsgroups: comp.databases.postgresql.sql Subject: Re: How to represent a tree-structure in a relational database Date: Thu, 28 Dec 2000 09:26:20 -0500 Organization: Yellowbank Lines: 42 Message-ID: <3A4B4D8C.9E542934@yellowbank.com> References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Trace: news.tht.net 978013581 78695 138.110.30.68 (28 Dec 2000 14:26:21 GMT) X-Complaints-To: scrappy@hub.org X-Mailer: Mozilla 4.75 [en] (X11; U; Linux 2.4.0-test9 i686) X-Accept-Language: en To: pgsql-sql@postgresql.org X-Archive-Number: 200012/304 X-Sequence-Number: 644 Stuart Statman wrote: > > I would suggest, instead, to create a table that represents your hierarchy > without adding columns. For example : > > create table Category ( > CategoryID int4 not null primary key, > ParentCategoryID int4 not null REFERENCES Category (CategoryID), > CategoryName varchar(100) > ); Another possibility would be to use two tables to represent the data structure. CREATE SEQUENCE category_node_id_seq; CREATE TABLE category_node ( name TEXT NOT NULL, id INTEGER DEFAULT NEXTVAL('category_node_id_seq') PRIMARY KEY ); CREATE TABLE category_edge ( parent INTEGER NOT NULL REFERENCES category_node(id), child INTEGER NOT NULL REFERENCES category_node(id) ); This structure is more 'normal' in the sense that nodes without children (in a tree, the leaf nodes) don't have records in the edge table. What either of these structures allow to do is create directed graph structures. If you'd like to constrain this structure to be a tree, you have to enforce that restriction with procedural code. -Ron-