Sub topic 10
Foreign Keys and Referential Actions
This chapter assumes you know what a primary key and a candidate key are, and that you can read basic CREATE TABLE statements. It covers how a foreign key links two tables, what the database does when a referenced row changes, and the cases GATE questions like to test.
What a Foreign Key Guarantees
A foreign key is an attribute (or set of attributes) in one relation, the referencing relation, whose values must match the values of a candidate key, usually the primary key, in another relation, the referenced relation. The two relations can be the same table.
The referential integrity rule says that every non-null foreign key value must appear as a key value in the referenced relation. Informally, you cannot point at a row that does not exist.
Three details matter:
- The foreign key may be NULL unless it is declared
NOT NULL. A NULL means "no reference", and it is allowed. - The foreign key does not need to be unique in the referencing table. Many employees can share one department.
- The referenced attributes must be a primary key or a
UNIQUEcolumn set. Otherwise the target row would not be identified unambiguously.
The foreign key column and the referenced column need compatible domains, but they do not need the same name.
A Running Example
CREATE TABLE department (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(50) NOT NULL UNIQUE
);
CREATE TABLE employee (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50) NOT NULL,
salary NUMERIC(10,2) CHECK (salary > 0),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES department(dept_id)
ON DELETE SET NULL
ON UPDATE CASCADE
);Here employee is the referencing table and department is the referenced table. The foreign key employee.dept_id may hold NULL, so an employee can exist with no department.
Which Operations Can Violate the Constraint
Not every operation can break referential integrity. The table below is worth memorizing for GATE.
| Operation | On referenced table (department) | On referencing table (employee) |
|---|---|---|
| Insert | Cannot violate | Can violate, if the new foreign key value has no matching parent |
| Delete | Can violate, if child rows still point to the deleted row | Cannot violate |
| Update | Can violate, if the key value changes and children still use the old value | Can violate, if the foreign key is changed to a value with no parent |
So inserting into the parent and deleting from the child are always safe with respect to this constraint.
Referential Actions
When a delete or update on the referenced table would leave dangling references, the database either rejects the operation or applies a referential action to the child rows. You declare the action with ON DELETE and ON UPDATE.
| Action | Effect when the parent row is deleted or its key updated |
|---|---|
| `NO ACTION` | The operation is rejected if it would leave a dangling reference. The check happens at the end of the statement, and may be deferred to commit if the constraint is deferrable. This is the default. |
| `RESTRICT` | The operation is rejected immediately. The check cannot be deferred. |
| `CASCADE` | The change propagates. A delete removes the child rows. A key update rewrites the child foreign key values. |
| `SET NULL` | The child foreign key values become NULL. The column must allow NULL. |
| `SET DEFAULT` | The child foreign key values become the column's default value. That default must itself match an existing parent row, or the operation fails. |
In GATE questions, NO ACTION and RESTRICT are usually treated the same way: the delete is refused.
Tracing the Example
Suppose department holds (10, 'Sales') and (20, 'HR'), and employee holds (1, 'Asha', 5000, 10) and (2, 'Ravi', 4000, 10).
DELETE FROM department WHERE dept_id = 10;triggersON DELETE SET NULL. Both employees remain, and both now havedept_id = NULL.UPDATE department SET dept_id = 30 WHERE dept_id = 20;triggersON UPDATE CASCADE. Any employee in department 20 now hasdept_id = 30.INSERT INTO employee VALUES (3, 'Meena', 3000, 99);is rejected, because department 99 does not exist.
Cascades Can Chain
A cascade on one table can trigger a further action on a table that references the child. Consider the weak entity from the ER mapping chapter.
CREATE TABLE dependent (
emp_id INT,
dependent_name VARCHAR(50),
relationship VARCHAR(20),
PRIMARY KEY (emp_id, dependent_name),
FOREIGN KEY (emp_id) REFERENCES employee(emp_id)
ON DELETE CASCADE
);Deleting a department with ON DELETE CASCADE on employee would delete the employees. Their dependent rows would then be deleted too, because of the second cascade. The whole chain succeeds only if every step is allowed. If any step in the chain is RESTRICT or NO ACTION and has a matching child row, the entire original statement fails and is rolled back.
Choosing an Action
The right action follows from the meaning of the relationship.
- Use
CASCADEwhen the child cannot exist without the parent. Weak entities and order line items are typical cases. - Use
SET NULLwhen the child is independent but the link is optional, such as an employee whose department is dissolved. This needs partial participation, so the foreign key must be nullable. - Use
RESTRICTorNO ACTIONwhen deleting a parent with children is probably a mistake, such as deleting a customer who still has invoices. SET NULLconflicts with total participation of the child. If every employee must belong to a department, the foreign key isNOT NULL, andSET NULLis not allowed.
Common Errors
- Declaring
SET NULLon aNOT NULLcolumn. The definition is invalid, or the delete fails at run time. - Referencing a non-key column. A foreign key must target a primary key or a
UNIQUEcolumn set. - Assuming a NULL foreign key violates the rule. It does not. NULL means no reference.
- Forgetting that composite foreign keys match as a unit. In a composite foreign key, all columns together must match one parent row. With the default
MATCH SIMPLEbehavior in SQL, if any column is NULL the check is skipped. - Creating circular references. Two tables that reference each other need the foreign key added later with
ALTER TABLE, or a deferrable constraint, so the first insert can succeed. - Cascade loops and surprises. A long cascade chain can delete far more rows than intended. Read the chain before you declare it.
Self-Referencing Foreign Keys
A foreign key can point to its own table. A manager column in employee is the usual example.
CREATE TABLE staff (
staff_id INT PRIMARY KEY,
staff_name VARCHAR(50) NOT NULL,
manager_id INT,
FOREIGN KEY (manager_id) REFERENCES staff(staff_id)
ON DELETE SET NULL
);The top manager has manager_id = NULL. Because NULL is allowed, the first row can be inserted without a parent. Deleting a manager sets the subordinates' manager_id to NULL.
Exercise
Relation R(A, B) has primary key A. Relation S(C, D) has primary key C, and D is a foreign key referencing R(A) with ON DELETE CASCADE. R contains the rows (1, x), (2, y), and S contains (10, 1), (11, 1), (12, 2). The statement DELETE FROM R WHERE A = 1 is executed. Which rows remain in S? Then say what would happen if the action were ON DELETE RESTRICT instead.
Show answer
With CASCADE, the rows of S whose D equals 1 are deleted, so (10, 1) and (11, 1) are removed. Only (12, 2) remains. With RESTRICT, the DELETE on R is rejected because S rows still reference A = 1, so both R and S are unchanged.
Exercise
For the foreign key employee.deptid referencing department.deptid, list which of these operations can violate referential integrity: (a) insert into employee, (b) delete from employee, (c) insert into department, (d) delete from department.
Show answer
(a) and (d). Inserting a child row with a missing parent value violates the rule, and deleting a parent row that children still reference violates it. Deleting a child row and inserting a parent row can never violate referential integrity.