Professional Documents
Culture Documents
deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behavior of the database server prevents you from deleting data in a table if other tables reference it. If you specify this option, later when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table. The principal advantage to the cascading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions. For example, the all_candy table contains the candy_num column as a primary key. The hard_candy table refers to the candy_num column as a foreign key. The following CREATE TABLE statement creates the hard_candy table with the cascading-delete option on the foreign key:
CREATE TABLE all_candy (candy_num SERIAL PRIMARY KEY, candy_maker CHAR(25)); CREATE TABLE hard_candy (candy_num INT, candy_flavor CHAR(20), FOREIGN KEY (candy_num) REFERENCES all_candy ON DELETE CASCADE)
Because ON DELETE CASCADE is specified for the dependent table, when a row of the all_candy table is deleted, the corresponding rows of the hard_candy table are also deleted. For information about syntax restrictions and locking implications when you delete rows from tables that have cascading deletes, see Considerations When Tables Have Cascading Deletes.
Note the 'ON DELETE RESTRICT' which will prevent you from deleting a school if there is a student going to that school. First look at what's in the tables:
SELECT * FROM school; SELECT * FROM student;
If you try the above, you should see 'ERROR: school_exists referential integrity violation - key in school still referenced from student' and notice that nothing was deleted. If you want to try the above more than once, the following may be handy:
DROP DROP DROP DROP SEQUENCE school_id_seq; TABLE school; SEQUENCE student_id_seq; TABLE student;
or
ON UPDATE RESTRICT would prevent UPDATE school SET school_id = 20 WHERE school_id = 1 from proceeding if there were any students with a school_id of 1.
You might be able to guess that ON UPDATE CASCADE would allow the UPDATE school SET school_id = 20 WHERE school_id = 1 to proceed, but it would also update the school_id field in the student table appropriately.
delete restrict
by DEFAULT the "on delete restrict" option is used in Oracle. In other words if you try to delete a parent record, and the primary key of that record is accessed by the foreign key(s) of any children, the application will not allow you to delete that parent record if you do not have any constraints explicitly written . You must write something like ON DELETE CASCADE (or other referential integity constraints) if you wish to delete a parent record refernced by children records.