Sub topic 19
Common mistakes and how to avoid them
This chapter collects the key-related errors that appear most often in real schemas. It assumes you can write CREATE TABLE statements with primary keys and foreign keys, know the ON DELETE actions, and can join tables. Examples use PostgreSQL syntax.
Most of these mistakes share one trait: the database accepts them without complaint. The damage shows up months later as duplicate rows, orphaned data, slow deletes, or lost history.
Mistakes with primary keys
No primary key at all
A table without a primary key allows two identical rows. You then cannot update or delete one of them without affecting the other, and no foreign key can point at the table. Every table should have one, including junction tables and small lookup tables.
A surrogate key with no natural uniqueness rule
A generated customer_id guarantees that each row has a unique number. It says nothing about whether two rows describe the same real customer. If you add a surrogate key and drop the constraint on the natural identifier, duplicates slip in:
CREATE TABLE customers_weak (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL,
name VARCHAR(100) NOT NULL
);
INSERT INTO customers_weak (email, name) VALUES ('[email protected]', 'Ana');
INSERT INTO customers_weak (email, name) VALUES ('[email protected]', 'Ana');Both inserts succeed. The fix is to keep email VARCHAR(255) NOT NULL UNIQUE, as in the earlier customers table. Treat the surrogate key as the row's internal handle and the unique constraint as the business rule.
Using a changeable value as the key
Emails, phone numbers, and usernames change. If such a value is the primary key, every referencing row must change with it, which means ON UPDATE CASCADE across many tables or a painful migration. Use a natural key only when the value is truly stable, such as an ISO country code. Otherwise use a surrogate key and a UNIQUE constraint.
Giving meaning to surrogate values
Do not rely on identity values being gapless, ordered by business time, or reusable. Rolled-back inserts and failed statements leave gaps in sequences. If you need a gapless invoice number, that is a separate business column with its own generation logic.
Mistakes with foreign keys
Relationships that exist only in your head
A column named customer_id in orders is only a naming convention. Without REFERENCES, the database will store 999 even if no such customer exists. Orphaned rows then appear, and queries that use an inner join silently drop them.
You can check an existing table for orphans with a left join:
SELECT o.order_id, o.customer_id
FROM orders AS o
LEFT JOIN customers AS c ON c.customer_id = o.customer_id
WHERE c.customer_id IS NULL;After you clean up the orphans, add the constraint. On a large live table, PostgreSQL lets you add it without checking old rows first, then validate separately:
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT fk_orders_customer;NOT VALID enforces the rule for new and changed rows immediately. VALIDATE CONSTRAINT then checks the existing rows with a weaker lock than a plain ADD CONSTRAINT takes.
Mismatched column types
The referencing column must have a type compatible with the referenced key. An INTEGER column pointing at a BIGINT key may work in some databases, but it invites overflow and slow comparisons. A TEXT column pointing at an integer key is rejected. Declare the foreign key with exactly the same type as the key it references.
Referencing a column that is not unique
A foreign key must point to a primary key or a UNIQUE column set. Otherwise the database could not tell which parent row you mean, and it rejects the declaration.
Forgetting the NOT NULL
A foreign key column accepts NULL unless you say otherwise, and a NULL foreign key skips the check entirely. If every order must have a customer, write customer_id INTEGER NOT NULL REFERENCES .... Reserve nullable foreign keys for relationships that really are optional, such as manager_id for a top-level employee.
In a composite foreign key, the default matching rule (MATCH SIMPLE) skips the check if any one column is NULL. Mark every column of a composite foreign key NOT NULL unless you want that behavior.
Storing a list in one column
A column such as product_ids holding '3,7,12' cannot carry a foreign key, so nothing validates its entries. It also cannot be indexed usefully for joins. Use a junction table with a composite primary key instead, like order_items.
Mistakes with delete and update actions
Cascading too far
ON DELETE CASCADE is correct for rows that have no meaning without their parent, such as order_items under an orders row. It is dangerous when applied to history. If orders.customer_id cascaded, deleting one customer would erase their entire order record, including data that finance may need.
Prefer the default NO ACTION or RESTRICT for business records, and mark customers inactive with a status column instead of deleting them. Cascades can also chain across several tables, so trace the whole path before adding one.
Not thinking about what a deletion means
Each foreign key forces a decision: should the delete be blocked, should the child rows go too, or should the link be cleared? SET NULL requires a nullable column, and SET DEFAULT requires a default that points at an existing parent row. A declaration that conflicts with the column definition fails or misbehaves, so decide the column's nullability first.
Mistakes with performance and queries
No index on the foreign key column
PostgreSQL indexes the referenced primary key but not the referencing column. Without CREATE INDEX idx_orders_customer_id ON orders (customer_id);, each parent delete scans the whole child table to check for references, and joins from parent to child are slower. MySQL's InnoDB creates this index for you. SQL Server and Oracle do not.
You can skip the index on a tiny table, or when you never join or delete in that direction. The cost is extra write work, so add it on purpose, not by reflex.
Joins that multiply rows
Joining orders to order_items returns one row per item. Summing an order-level column after that join counts it once per item. Aggregate each side separately, or sum only the item-level column, such as quantity or line price.
Quick reference
| Mistake | Symptom | Fix |
|---|---|---|
| No primary key | Duplicate rows, no safe single-row update | Add a primary key |
| Surrogate key only | Duplicate real-world entities | Add `UNIQUE` on the natural identifier |
| No `REFERENCES` | Orphaned rows | Add the foreign key, using `NOT VALID` if needed |
| Nullable required link | Rows with no parent | Add `NOT NULL` |
| Wrong `CASCADE` | History deleted | Use `RESTRICT` or soft deletes |
| Unindexed foreign key | Slow joins and parent deletes | Create an index |
| List in one column | No validation | Use a junction table |
Exercise
A table invoices has a column customer_id INTEGER with no REFERENCES clause, and some rows contain customer IDs that do not exist. Write the steps to repair the schema without blocking writes for long.
Show answer
First find the orphans with a LEFT JOIN to customers where the customer's key IS NULL, and fix or remove them. Then run ALTER TABLE invoices ADD CONSTRAINT fkinvoicescustomer FOREIGN KEY (customerid) REFERENCES customers (customerid) NOT VALID, which enforces the rule for new and changed rows. Finally run ALTER TABLE invoices VALIDATE CONSTRAINT fkinvoicescustomer to check the existing rows. If every invoice needs a customer, also set the column NOT NULL, and add an index on invoices (customer_id).
Exercise
Why is ON DELETE CASCADE on orders.customer_id usually a poor choice, while it fits order_items.order_id?
Show answer
An order item has no meaning without its order, so removing it with the order is correct. Order history must survive for accounting and support even if a customer record is retired, so cascading from customers to orders could erase it. Use RESTRICT or NO ACTION there and mark customers inactive instead.