473,378 Members | 1,400 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Recursive FOREIGN KEY?

I have a table that will have a parent/child relationship (specifically
a recursive collection of categories) and was wondering if I can
reference a key in the same table ...

CREATE TABLE categories (
categoryID integer PRIMARY KEY,
parentID integer REFERENCES categories (categoryID) ON DELETE CASCADE,

...
);

Is this supported? Any comments from people out there who have created
such setups? I'm new to PGSQL and looking hard at converting from MySQL
so all of these fun features are new to me :)

Thanks!

--Joe

--
Joe Stump, President
JCS Solutions
http://www.jcssolutions.com
(734) 786 0176
---------------------------(end of broadcast)---------------------------
TIP 4: Don't 'kill -9' the postmaster

Nov 23 '05 #1
5 11196
This is possible and works as expected but did require a mild
work-around ...

CREATE TABLE categories (
categoryID integer PRIMARY KEY,
parentID integer,
setID integer REFERENCES categories_sets (setID) ON DELETE CASCADE,
name char(255) NOT NULL
);

INSERT INTO categories VALUES (0,0,0,'DEFAULT');

CREATE INDEX categories_parentID ON categories (categoryID);
CREATE INDEX categories_setID ON categories (setID);

ALTER TABLE categories
ADD CONSTRAINT categories_parentID
FOREIGN KEY (parentID) REFERENCES categories (categoryID) ON DELETE
CASCADE;
I had to insert the initial record and then add the foreign key
restraint after inserting the initial record was created (0 being the
first level of the category structure) - deletes cascade recursively as
expected (sweet).

Thanks!

--Joe
On Sat, 2004-04-03 at 19:46, Joe Stump wrote:
I have a table that will have a parent/child relationship (specifically
a recursive collection of categories) and was wondering if I can
reference a key in the same table ...

CREATE TABLE categories (
categoryID integer PRIMARY KEY,
parentID integer REFERENCES categories (categoryID) ON DELETE CASCADE,

...
);

Is this supported? Any comments from people out there who have created
such setups? I'm new to PGSQL and looking hard at converting from MySQL
so all of these fun features are new to me :)

Thanks!

--Joe

--
Joe Stump, President
JCS Solutions
http://www.jcssolutions.com
(734) 786 0176
---------------------------(end of broadcast)---------------------------
TIP 4: Don't 'kill -9' the postmaster

--
--
Joe Stump, President
JCS Solutions
p. (734) 786 0176
f. (520) 844 9344
http://www.jcssolutions.com
---------------------------(end of broadcast)---------------------------
TIP 5: Have you checked our extensive FAQ?

http://www.postgresql.org/docs/faqs/FAQ.html

Nov 23 '05 #2
Joe Stump <jo*@joestump.net> writes:
I had to insert the initial record and then add the foreign key
restraint after inserting the initial record was created (0 being the
first level of the category structure) -


Why? It worked fine for me without any workaround ...

regression=# CREATE TABLE categories (
regression(# categoryID integer PRIMARY KEY,
regression(# parentID integer REFERENCES categories (categoryID) ON DELETE CASCADE,
regression(# name text);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "categories_pkey" for table "categories"
CREATE TABLE
regression=# insert into categories values(0,0,'root');
INSERT 1349044 1
regression=# insert into categories values(1,2,'root');
ERROR: insert or update on table "categories" violates foreign key constraint "$1"
DETAIL: Key (parentid)=(2) is not present in table "categories".
regression=# insert into categories values(1,0,'root');
INSERT 1349046 1
regression=#

regards, tom lane

---------------------------(end of broadcast)---------------------------
TIP 4: Don't 'kill -9' the postmaster

Nov 23 '05 #3
I was getting an error on the parentID reference because there were no
records to reference in the first place. Odd.

--Joe

On Sat, 2004-04-03 at 23:36, Tom Lane wrote:
Joe Stump <jo*@joestump.net> writes:
I had to insert the initial record and then add the foreign key
restraint after inserting the initial record was created (0 being the
first level of the category structure) -


Why? It worked fine for me without any workaround ...

regression=# CREATE TABLE categories (
regression(# categoryID integer PRIMARY KEY,
regression(# parentID integer REFERENCES categories (categoryID) ON DELETE CASCADE,
regression(# name text);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "categories_pkey" for table "categories"
CREATE TABLE
regression=# insert into categories values(0,0,'root');
INSERT 1349044 1
regression=# insert into categories values(1,2,'root');
ERROR: insert or update on table "categories" violates foreign key constraint "$1"
DETAIL: Key (parentid)=(2) is not present in table "categories".
regression=# insert into categories values(1,0,'root');
INSERT 1349046 1
regression=#

regards, tom lane

--
--
Joe Stump, President
JCS Solutions
p. (734) 786 0176
f. (520) 844 9344
http://www.jcssolutions.com
---------------------------(end of broadcast)---------------------------
TIP 1: subscribe and unsubscribe commands go to ma*******@postgresql.org

Nov 23 '05 #4
Joe Stump <jo*@joestump.net> writes:
I was getting an error on the parentID reference because there were no
records to reference in the first place. Odd.


It should work, because the FK check is an end-of-statement check and
should consider the just-inserted row as available for referencing.
What PG version are you using, and can you show the exact sequence of
operations that produces a failure for you?

regards, tom lane

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

Nov 23 '05 #5
What you say makes sense - I must have been doing something screwy
because it works fine now.

--Joe

On Sun, 2004-04-04 at 00:44, Tom Lane wrote:
Joe Stump <jo*@joestump.net> writes:
I was getting an error on the parentID reference because there were no
records to reference in the first place. Odd.


It should work, because the FK check is an end-of-statement check and
should consider the just-inserted row as available for referencing.
What PG version are you using, and can you show the exact sequence of
operations that produces a failure for you?

regards, tom lane

--
--
Joe Stump, President
JCS Solutions
p. (734) 786 0176
f. (520) 844 9344
http://www.jcssolutions.com
---------------------------(end of broadcast)---------------------------
TIP 8: explain analyze is your friend

Nov 23 '05 #6

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

Similar topics

5
by: Magnus Lyck? | last post by:
Something really strange is happening to me (sometimes). I'm using Python 2.3.2 on NT 4.0 as well as win32all-157, adodbapi and db_row. During a recursive call to a method, it seems Python...
2
by: geoff | last post by:
The table creation script(at the end of this post) works fine on 4.0.1-alpha-win, but the foreign key constraints fail on 4.0.15-win. I am starting the server with the same command for both...
10
by: Bodza Bodza | last post by:
I'm having an argument with an incumbent self-taught programmer that it is OK to use null foreign keys in database design. My take is the whole point of a foreign key is that it's not supposed...
31
by: Robert Brown | last post by:
Let's say I have a type hierarchy: (just an example) the general entity customer: CREATE TABLE customer(customer_id int, customer_name varchar(250), customer_type int) three specific...
4
by: JayCallas | last post by:
Went looking for an answer but not really sure what phrases to look for. Just decided to post my question. I have a collection of groups which contain items. I also have a collection of users...
0
by: Scott Ribe | last post by:
I've got a problem which I think may be a bug in Postgres, but I wonder if I'm missing something. Two tables, A & B have foreign key relations to each other. A 3rd table C, inherits from A. A...
3
by: Robert Ludig | last post by:
I am fairly new to SQL and I am currently trying to create a SQL table (using Microsoft SQL) that has a recursive relationship, let me try to explain: I have a piece of Data let's call it "Item"...
4
by: Mike | last post by:
Hello, I'm trying to use a recursive CTE to find some data but I am having trouble crafting the CTE; maybe what I want isn't possible. I have the following tables: EMPLOYEE (int ID, int...
1
by: =?iso-8859-15?Q?Paul_Gr=F8stad?= | last post by:
Hi. I'm very new to Oracle (and databases in general), and I have a problem that most of you people probably will find very easy, but I just can't figure it out... I'm trying to create a...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.