Sub topic 10
Linking Tables with FOREIGN KEY and ON DELETE
This chapter assumes you can write a basic CREATE TABLE statement and that you know how PRIMARY KEY and UNIQUE constraints work. It covers how a foreign key links a child table to a parent table, what Oracle checks on each DML statement, the ON DELETE options, and the errors you will meet most often.
What a foreign key enforces
A foreign key is a constraint on one or more columns of a child table. Each non-null value in those columns must match a value in a parent key. The parent key must be a PRIMARY KEY or UNIQUE constraint on the parent table. This is why the concept graph places foreign keys after both of those constraints.
A foreign key guarantees referential integrity. You cannot insert an employee that points to a department that does not exist. You also cannot delete a department that employees still point to, unless you chose an ON DELETE action that handles those employees.
The examples in this chapter use the departments and employees tables from earlier in the tutorial.
CREATE TABLE departments (
department_id NUMBER GENERATED ALWAYS AS IDENTITY,
department_name VARCHAR2(100) NOT NULL,
CONSTRAINT departments_pk PRIMARY KEY (department_id),
CONSTRAINT departments_name_uk UNIQUE (department_name)
);The departments table is the parent. Its primary key is department_id.
Declaring a foreign key
You can declare a foreign key inline, as part of a column definition, or out of line, as a separate clause. The out-of-line form is the one used here because it lets you name the constraint and, for composite keys, list several columns.
CREATE TABLE employees (
employee_id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY
(START WITH 1000 INCREMENT BY 1 CACHE 20),
email VARCHAR2(255) NOT NULL,
salary NUMBER(10,2),
status VARCHAR2(10) DEFAULT 'ACTIVE' NOT NULL,
hire_date DATE DEFAULT SYSDATE NOT NULL,
department_id NUMBER,
CONSTRAINT employees_pk PRIMARY KEY (employee_id),
CONSTRAINT employees_email_uk UNIQUE (email),
CONSTRAINT employees_salary_ck CHECK (salary >= 0),
CONSTRAINT employees_status_ck CHECK (status IN ('ACTIVE', 'INACTIVE')),
CONSTRAINT employees_dept_fk FOREIGN KEY (department_id)
REFERENCES departments (department_id)
ON DELETE SET NULL
);The clause has three parts:
FOREIGN KEY (department_id)names the child column.REFERENCES departments (department_id)names the parent table and the parent key columns.ON DELETE SET NULLsays what to do when a parent row is deleted.
The inline form omits FOREIGN KEY and the column list, as in department_id NUMBER CONSTRAINT employees_dept_fk REFERENCES departments (department_id). If you leave out the parent column list, Oracle references the parent's primary key. Naming the columns anyway makes the statement easier to read.
The child and parent columns must have compatible data types. A NUMBER child column referencing a VARCHAR2 parent key is rejected. The two sides do not have to have the same column name.
Rules Oracle applies
The parent key must exist before the child table is created. Create departments first.
A foreign key column can be NULL. A row whose foreign key is NULL is not checked against the parent, so it is allowed. In employees, department_id is nullable, so an employee can have no department. To make the relationship mandatory, add NOT NULL to the child column.
For a composite foreign key, which has more than one column, the rule is different. If every column is NULL, the row is not checked. If only some columns are NULL, Oracle does not check the row either under the default MATCH SIMPLE-like behavior, which can let inconsistent combinations through. Add NOT NULL to each column of a composite foreign key if you want full enforcement.
What happens on each statement
Oracle checks the foreign key when either side changes.
| Statement | Table | Check |
|---|---|---|
| `INSERT` | Child | The new foreign key value must exist in the parent, or be `NULL`. |
| `UPDATE` of the foreign key column | Child | The new value must exist in the parent, or be `NULL`. |
| `DELETE` | Parent | Depends on the `ON DELETE` clause. |
| `UPDATE` of the parent key | Parent | Rejected if any child row still references the old value. |
| `DROP TABLE` | Parent | Rejected unless you add `CASCADE CONSTRAINTS`. |
The fourth row matters. Oracle has no ON UPDATE clause. You cannot ask Oracle to change child values automatically when a parent key changes. In practice, primary keys should not change, which is one reason surrogate keys such as identity columns work well. If you must change a parent key, you have to insert a new parent row, move the child rows to it, and then delete the old parent row.
Choosing an ON DELETE action
Oracle supports three behaviors when a parent row is deleted.
| Clause | Effect on child rows |
|---|---|
| (none, the default) | The delete fails with ORA-02292 if any child row references the parent. |
| `ON DELETE CASCADE` | Child rows are deleted along with the parent. |
| `ON DELETE SET NULL` | The foreign key columns in the child rows are set to `NULL`. |
Oracle has no ON DELETE SET DEFAULT, and it has no ON DELETE RESTRICT keyword. The default behavior is the restrictive one.
The default: no action
With no ON DELETE clause, the parent row cannot be deleted while children exist. This is the safest choice for data that should never disappear by accident, such as customers with orders.
CREATE TABLE orders (
order_id NUMBER GENERATED ALWAYS AS IDENTITY,
customer_id NUMBER NOT NULL,
CONSTRAINT orders_pk PRIMARY KEY (order_id)
);If orders.customer_id referenced a customers table with no ON DELETE clause, deleting a customer that has orders would raise ORA-02292: integrity constraint (SCHEMA.CONSTRAINT_NAME) violated - child record found. The message includes the constraint name, which is a good reason to name your constraints.
CASCADE
Use ON DELETE CASCADE when the child rows have no meaning without the parent. Order lines belong to an order, so deleting the order should delete its lines.
CREATE TABLE order_lines (
order_id NUMBER NOT NULL,
line_no NUMBER NOT NULL,
product_id NUMBER NOT NULL,
quantity NUMBER(6) NOT NULL,
CONSTRAINT order_lines_pk PRIMARY KEY (order_id, line_no),
CONSTRAINT order_lines_ord_fk FOREIGN KEY (order_id)
REFERENCES orders (order_id)
ON DELETE CASCADE
);Cascades are recursive. If order_lines had its own children with ON DELETE CASCADE, they would be deleted too. A single delete can therefore remove many rows across many tables, and the delete takes longer and holds more locks than it appears to. Row-level delete triggers on the child tables fire for each cascaded row.
SET NULL
Use ON DELETE SET NULL when the child row should survive and the link is optional. This is the action in employees_dept_fk. If a department is deleted, its employees remain, with department_id set to NULL.
SET NULL requires the foreign key column to accept NULL. If the column is NOT NULL, Oracle cannot set it, and the delete fails with ORA-01407. A NOT NULL foreign key column is therefore compatible with the default and with CASCADE, but not with SET NULL.
A worked example
This script inserts a department and an employee, then deletes the department.
INSERT INTO departments (department_name) VALUES ('Sales');
INSERT INTO employees (email, department_id)
SELECT '[email protected]', department_id
FROM departments
WHERE department_name = 'Sales';
DELETE FROM departments WHERE department_name = 'Sales';
SELECT email, department_id FROM employees;Because employees_dept_fk uses ON DELETE SET NULL, the delete succeeds, and the final query returns the employee with a NULL department. With the default action, the same delete would fail with ORA-02292.
An insert that names a department that does not exist fails with ORA-02291: integrity constraint (SCHEMA.EMPLOYEES_DEPT_FK) violated - parent key not found.
Common errors
| Error | Meaning | Typical fix |
|---|---|---|
| ORA-02291 | Parent key not found when inserting or updating a child. | Insert the parent row first, or correct the value. |
| ORA-02292 | Child record found when deleting or updating a parent. | Delete or reassign the children, or choose `CASCADE` or `SET NULL`. |
| ORA-02270 | No matching unique or primary key for this column list. | Add a `PRIMARY KEY` or `UNIQUE` constraint on the parent columns. |
| ORA-02267 | Column type incompatible with referenced column type. | Make the data types match. |
| ORA-01407 | Cannot update a `NOT NULL` column to `NULL`, raised by `SET NULL`. | Make the column nullable or use another action. |
Performance: index the foreign key column
Oracle automatically creates an index for a primary key or unique constraint. It does not create one for a foreign key. Without an index on the child column, two things get slower:
- Deleting a parent row requires Oracle to search the child table for matching rows. Without an index, that is a full table scan for every deleted parent.
- In older behavior, an unindexed foreign key could cause a table-level lock on the child table when the parent key is updated or deleted. Current releases take a lighter lock, but contention can still occur.
Create the index yourself when the child table is large or the parent is deleted often.
CREATE INDEX employees_dept_ix ON employees (department_id);Joins from parent to child also benefit from this index.
Self-referencing and deferrable keys
A foreign key can point to the same table, which models hierarchies such as employee and manager. The next chapters on ALTER TABLE and constraint states add such a key with DEFERRABLE INITIALLY DEFERRED, which delays the check until commit. That setting lets you insert rows in any order inside one transaction.
Summary of the diagram
The flow below shows what Oracle does when you delete a parent row.
Key points
- A foreign key must reference a primary key or unique constraint, and a
NULLforeign key value skips the check. - Oracle offers three delete behaviors: the default error,
CASCADE, andSET NULL. It has noON UPDATEaction. SET NULLneeds a nullable column.- Name foreign keys so error messages identify the broken rule.
- Index foreign key columns yourself.
Exercise
A table invoice_items has a column invoice_id NUMBER NOT NULL that references invoices (invoice_id). A developer adds ON DELETE SET NULL to the foreign key. What happens when an invoice that has items is deleted, and which clause would let you remove the invoice together with its items?
Show answer
The delete fails with ORA-01407, because Oracle cannot set the NOT NULL column invoice_id to NULL. Use ON DELETE CASCADE to delete the invoice and its items together.
Exercise
You change the primary key value of a department row that still has employees, using UPDATE departments SET departmentid = 500 WHERE departmentid = 10. Which error do you get, and why does Oracle not fix the employee rows for you?
Show answer
The update fails with ORA-02292 (child record found). Oracle has no ON UPDATE action for foreign keys, so child rows are never changed automatically. You must insert a new parent row, move the children to it, and delete the old parent row.