Sub topic 3
Joining Along Keys, Nullable Links, Hierarchies, and Constraint Changes
This chapter assumes you can write SELECT, INSERT, UPDATE, and DELETE, create tables with CREATE TABLE, and read a JOIN. The examples use PostgreSQL syntax. The dialect table at the end lists where the other databases differ.
Joining along keys
A join matches rows where a foreign key equals a primary key:
SELECT c.name, o.order_id, o.ordered_at
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
ORDER BY o.ordered_at;An inner JOIN drops customers with no orders. A LEFT JOIN keeps them and fills the order columns with NULL.
Optional relationships and NULL foreign keys
A foreign key column can allow NULL. A NULL value means "no related row." A NULL foreign key skips the referential check, so the row is accepted without a parent.
Self-referencing keys for hierarchies
A table can reference itself. In this employees example, a NULL manager_id marks the top of the hierarchy:
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
);
SELECT e.name, m.name AS manager
FROM employees AS e
LEFT JOIN employees AS m ON m.employee_id = e.manager_id;Indexing foreign key columns
Joins and parent-row deletes scan the child table unless an index exists on the foreign key column. PostgreSQL does not create that index for you:
CREATE INDEX idx_orders_customer_id ON orders (customer_id);Adding and dropping constraints on existing tables
Name a constraint so you can change it later. Adding a foreign key fails if existing rows already violate it:
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id);
ALTER TABLE orders
DROP CONSTRAINT fk_orders_customer;Deferrable constraints and circular references
Two tables can reference each other. A deferrable constraint checks at COMMIT instead of each statement, which lets both rows exist in one transaction:
CREATE TABLE departments (
department_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
head_id INTEGER
);
CREATE TABLE staff (
staff_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
department_id INTEGER NOT NULL REFERENCES departments (department_id)
DEFERRABLE INITIALLY DEFERRED
);
ALTER TABLE departments
ADD CONSTRAINT fk_head FOREIGN KEY (head_id) REFERENCES staff (staff_id)
DEFERRABLE INITIALLY DEFERRED;
BEGIN;
INSERT INTO departments (name, head_id) VALUES ('Sales', 1);
INSERT INTO staff (name, department_id) VALUES ('Ana', 1);
COMMIT;How MySQL, SQL Server, Oracle, and PostgreSQL differ
| Feature | PostgreSQL | MySQL (InnoDB) | SQL Server | Oracle |
|---|---|---|---|---|
| Creates index on FK automatically | No | Yes | No | No |
| Deferrable constraints | Yes | No | No | Yes |
| ON UPDATE CASCADE | Yes | Yes | Yes | No |
Common mistakes and how to avoid them
- Forgetting the index on a foreign key column, which slows joins and deletes.
- Allowing NULL in a foreign key that should be required.
- Using
ON DELETE CASCADEwithout knowing how many rows it removes. - Adding a foreign key to a table with orphaned rows, which fails.
- Assuming a deferrable constraint works in MySQL or SQL Server. It does not.
Exercise
A customer table has no orders yet. Which join returns that customer with NULL order columns: an inner JOIN or a LEFT JOIN from customers to orders?
Show answer
A LEFT JOIN from customers to orders. An inner JOIN drops customers with no matching orders.