RE: How to represent a tree-structure in a relational database

From: "Stuart Statman" <stu(at)slammedia(dot)com>
To: "Frank Joerdens" <frank(at)joerdens(dot)de>, <pgsql-sql(at)postgresql(dot)org>
Subject: RE: How to represent a tree-structure in a relational database
Date: 2000-12-13 19:38:18
Message-ID: NEBBJLPJHKIDLJDGCMKAKEIDCBAA.stu@slammedia.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

> What I am thinking now is that you would keep the index
> in a separate index table linked with the primary
> key in the articles table), which would have 6 or 7 fields
> initially, and that you'd add columns with the alter table
> command, if need be, to make the structure deeper.

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)
);

Add a CategoryID with an FK reference to this table, and your work is done.

Then adding, inserting, removing, or moving layers in the hierarchy becomes
quite simple. This also preserves hierarchical integrity, where subcategory
a of subcategory b will also remain a subcategory of category c if
subcategory b is a subcategory of subcategory c, where I'm not sure your
model will preserve or guarantee that. (Does that sentence deserve a prize?)

In general, if you know that you will need to periodically alter a table to
add columns, you should come up with a different model that doesn't require
adding columns.

Stuart Statman
Director of Software Development
Slam Media, Inc.

Attachment Content-Type Size
Stuart Statman.vcf text/x-vcard 482 bytes

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message miguel sofer 2000-12-13 19:44:02 Re: How to represent a tree-structure in a relational database
Previous Message Jie Liang 2000-12-13 19:27:32 plpgsql