473,788 Members | 2,820 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

self referencing table structure and constraints

I have a categories table that contains a FK to another category in the
same table, creating a hierarchy. At the very top is this row:

category_id | name | description | parent_id
-------------+------+-------------------------+-----------
1 | ROOT | The top level category. | 0

There is no record with category_id 0 because ROOT is at the top of the
tree. I'd like to set up a constraint on this table so that every
category has to have a parent_id and it would be impossible to delete a
category if it had subcategories. The problem is that this root
category violates that constraint. Is there a way to setup the
constraint so that it constrains every record except for forcing the
root category to point at a real parent category?
I thought of pointing ROOT to itself, but since we have some
recursive code that starts at a given category id and moves up the tree
it will hit the ROOT category and loop forever. I'd like to fix this
by constraining the database so that even working from psql it would be
difficult to damage this table by hand.
Are there any widely used techniques for dealing with this type of
constraint?
Thanks,
-M@
---------------------------(end of broadcast)---------------------------
TIP 1: subscribe and unsubscribe commands go to ma*******@postg resql.org

Nov 23 '05 #1
2 2438

On Thu, 23 Sep 2004, Matthew Hixson wrote:
I have a categories table that contains a FK to another category in the
same table, creating a hierarchy. At the very top is this row:

category_id | name | description | parent_id
-------------+------+-------------------------+-----------
1 | ROOT | The top level category. | 0
There is no record with category_id 0 because ROOT is at the top of the
tree. I'd like to set up a constraint on this table so that every
category has to have a parent_id and it would be impossible to delete a
category if it had subcategories. The problem is that this root
category violates that constraint. Is there a way to setup the
constraint so that it constrains every record except for forcing the
root category to point at a real parent category?
Well, to simply have the root category not error, you could use NULL for
the parent_id if you're using a foreign key. However, it sounds like your
full problem is more complicated.

If you want to force that there always exists exactly 1 such row, it's
harder. Forcing that there's no more than 1 should be possible without
writing triggers (maybe a unique index on ((1)) where parent_id is null)
but I'm not sure how else to guarantee that there's at least 1 besides a
trigger.
I thought of pointing ROOT to itself, but since we have some
recursive code that starts at a given category id and moves up the tree
it will hit the ROOT category and loop forever. I'd like to fix this
by constraining the database so that even working from psql it would be
difficult to damage this table by hand.


Well, in that case you also may need to watch out for cycles. You can do
this with triggers, but handling concurrent changes might get tricky.

---------------------------(end of broadcast)---------------------------
TIP 3: if posting/reading through Usenet, please send an appropriate
subscribe-nomail command to ma*******@postg resql.org so that your
message can get through to the mailing list cleanly

Nov 23 '05 #2
On Sep 23, 2004, at 6:36 PM, Stephan Szabo wrote:

On Thu, 23 Sep 2004, Matthew Hixson wrote:
I have a categories table that contains a FK to another category in
the
same table, creating a hierarchy. At the very top is this row:

category_id | name | description | parent_id
-------------+------+-------------------------+-----------
1 | ROOT | The top level category. | 0


There is no record with category_id 0 because ROOT is at the top of
the
tree. I'd like to set up a constraint on this table so that every
category has to have a parent_id and it would be impossible to delete
a
category if it had subcategories. The problem is that this root
category violates that constraint. Is there a way to setup the
constraint so that it constrains every record except for forcing the
root category to point at a real parent category?


Well, to simply have the root category not error, you could use NULL
for
the parent_id if you're using a foreign key.


Okay, now I just feel silly. For some reason I was thinking that the
parent id couldn't be NULL either.
Thanks, this is exactly what I needed.
-M@
---------------------------(end of broadcast)---------------------------
TIP 7: don't forget to increase your free space map settings

Nov 23 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
11536
by: sreddy | last post by:
I am trying to write a sql query on self referencing table. Just to brief ..Database is related to a Hiring department of the Qwest company. I need to generate a Report used by in HR department to pay the employees who have referred the candidates for the jobs in their .. This report is used by the HR department to get the required
36
4657
by: toedipper | last post by:
Hello, I am designing a table of vehicle types, nothing special, just a list of unique vehicle types such as truck, lorry, bike, motor bike, plane, tractor etc etc For the table design I am proposing a single column table with a field name called vehicle_type and this will contain the vehicle type. Sot it will be
7
9228
by: Andrew Mayo | last post by:
Here's a really weird one for any SQL Server gurus out there... We have observed (SQL Server 2000) scenarios where a stored procedure which (a) begins a transaction (b) inserts some rows into a table (c) re-queries another table using a subquery which references the inserted table (correlated or not)
4
15839
by: maricel | last post by:
I have the following base table structure - DDL: CREATE TABLE "ADMINISTRATOR"."T1" ( "C1" INTEGER NOT NULL ) IN "TEST_TS" ; ALTER TABLE "ADMINISTRATOR"."T1" ADD PRIMARY KEY
2
3818
by: Paul Cook | last post by:
Hi, I have three tables: Countries: ID Country States: ID
10
6109
by: Macka | last post by:
A few pieces of information first: * I have a class called Folder which represents a row of data in a database table. The data access side of things is not an issue. * The table has a parent column which references itself (ie. Adjacency or parent/child model) * I have a public property called 'Parent' which returns me a new reference to a Folder instance containing the data of the parent row.
1
2485
by: Andrew Banks | last post by:
I have a database table with the following kind of structure CategoryID (int) Parent CategoryID (int) CategoryName (varchar) The table has a self referencing relationship between ParentCategoryID CategoryID. In C#.NET how can I loop through this table and list all categories,
0
1299
by: Doug Gault | last post by:
I've been very pleased to find that you can load an XML file into a DATASET using the XMLREAD method, but I'm having a problem when trying to load a file that contains self-referencing elements. Here is an excerpt from the .XSD file ... ================================================ XSD SCHEMA DOC ================================================
1
1995
by: vojinle | last post by:
Hi, Is there any example populating TreeView control from self-referencing database table? Table structure: ID Item_name Parent_ID
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10366
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9967
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4070
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3674
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.