On delete restrict SQL help

9.2k views Asked by At

I have the two following tables:

    Owner:

    O_ID P_ID
    Bob   Sam
    Steve Rex


    Pets

    P_ID O_ID
    Sam  Bob
    Rex  Steve

The second column of owners (P_ID) is a foreign key to the first column of pets (P_ID).

In DB2, I'm trying to add an ON_DELETE RESTRICT constraint, such that if someone were to try and delete an Owner in the owner table, if that owner were the owner of a pet, the delete operation would be rejected. I know I have to use the ON_DELETE RESTRICT command, but I'm at a loss of how to do so.

I've tried this:

ALTER TABLE OWNERS
ADD CONSTRAINT no_delete
FOREIGN KEY (P_ID)
REFERENCES PETS(P_ID)
ON DELETE RESTRICT

To no avail.

2

There are 2 answers

2
Mike Sherrill 'Cat Recall' On BEST ANSWER

Your syntax is correct. Your logic is wrong.

You want to prevent deleting an owner if it has a pet in the table "pets". To do that, you need to alter the table "pets", and add a foreign key constraint referencing the table "owners".

0
David Sky On

Catcall is correct, here's the correct ALTER TABLE command (tested in DB2 LUW v9.7):

ALTER TABLE pets ADD CONSTRAINT no_delete FOREIGN KEY (P_ID) REFERENCES owner(P_ID) ON DELETE RESTRICT;

Then when I tried to remove Steve from the owner table with the following command:

DELETE FROM owner where O_ID = 'Steve';

I received, as expected:

DB21034E The command was processed as an SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: SQL0532N A parent row cannot be deleted because the relationship "DB2INST1.PETS.NO_DELETE" restricts the deletion. SQLSTATE=23001

Then to make sure this is working completely as expected, I erased Steve's dog:

DELETE FROM pets WHERE O_ID = 'Steve'

And re-ran the attempt to remove Steve from the owner table, and it worked!