Sub topic 13
Optional Relationships and NULL Foreign Keys
Prerequisites and the basic model
This chapter assumes that you can create tables and use SELECT, INSERT, UPDATE, and DELETE. You should also understand rows, columns, data types, and NULL.
A foreign key is a column whose value must match a key in another table. It represents a relationship between rows. Sometimes that relationship is required. For example, every order might need a customer. Sometimes it is optional. An employee might have no manager because the employee is at the top of the organization.
A nullable foreign key allows either a matching parent key or NULL. NULL means “unknown or not applicable”; it does not mean zero or an empty string.
CREATE TABLE employees (
employee_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
manager_id INTEGER REFERENCES employees (employee_id)
ON DELETE SET NULL
);
INSERT INTO employees (name, manager_id)
VALUES
('Mina', NULL),
('Owen', 1);manager_id is optional because it does not have NOT NULL. Mina has no manager, while Owen reports to employee 1. The foreign key still prevents a non-NULL value from pointing to a nonexistent employee.
Required and optional relationships
The choice between NOT NULL and nullable determines whether a relationship is required.
| Definition | Meaning |
|---|---|
| `customer_id INTEGER NOT NULL REFERENCES customers(customer_id)` | Every child row must have a customer |
| `manager_id INTEGER REFERENCES employees(employee_id)` | A child row may have no manager |
A nullable foreign key does not allow arbitrary values. This insert is rejected if employee 999 does not exist:
INSERT INTO employees (name, manager_id)
VALUES ('Priya', 999);To remove Owen’s manager, set the foreign key to NULL:
UPDATE employees
SET manager_id = NULL
WHERE employee_id = 2;When querying optional relationships, use LEFT JOIN if you want to retain rows that have no parent. An ordinary JOIN excludes those rows because NULL does not equal any value, including another NULL.
SELECT employee.name,
manager.name AS manager_name
FROM employees AS employee
LEFT JOIN employees AS manager
ON manager.employee_id = employee.manager_id;Choosing the rule
Use a nullable foreign key when the relationship is genuinely optional. Do not use NULL to hide missing required data. If every order must have a customer, declare that foreign key NOT NULL and let the database enforce the rule.
Exercise
What happens when the employee referenced by manager_id is deleted with ON DELETE SET NULL?
Show answer
The employee row remains, and its manager_id is changed to NULL. The employee becomes a top-level employee.