Sub topic 15
How constraints relate to indexes
This chapter assumes you can write CREATE TABLE statements and know what PRIMARY KEY, UNIQUE, and FOREIGN KEY mean. It covers how the database enforces those rules and which indexes it creates or leaves out.
What an index is, and why constraints need one
An index is a separate data structure, usually a B-tree, that lets the database find rows by column value without reading the whole table. Consider this check: "does the email [email protected] already exist?" Without an index, the database would scan every row on every insert. With an index on email, it does a quick lookup.
Constraints that must test whether a value already exists therefore rely on an index:
- PRIMARY KEY and UNIQUE need to find an existing row with the same key.
- A FOREIGN KEY needs to find the referenced row in the parent table.
NOT NULL, DEFAULT, and CHECK look only at the row being written. They need no index.
Indexes created automatically
Most systems build an index when you declare a PRIMARY KEY or UNIQUE constraint. Take the customers table from earlier in the tutorial:
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);This statement produces two indexes: one for the primary key and one for the unique email. You did not write CREATE INDEX, but both exist. In PostgreSQL you can list them:
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'customers';The names are generated, such as customers_pkey and customers_email_key. If you name the constraint, the index usually takes the same name. That is one more reason to name constraints.
| Constraint | Index created automatically? | Purpose of the index |
|---|---|---|
| PRIMARY KEY | Yes, in all major systems | Fast lookup and duplicate detection |
| UNIQUE | Yes, in all major systems | Duplicate detection |
| FOREIGN KEY | Depends on the system | Not created in PostgreSQL, Oracle, or SQL Server |
| CHECK | No | Not needed |
| NOT NULL | No | Not needed |
Foreign keys and the missing index
The foreign key is where the gap appears. A foreign key column in the child table points at an indexed column in the parent, so lookups in the parent are fast. The child column itself may have no index.
MySQL with InnoDB is the exception. It creates an index on the foreign key column if none exists. PostgreSQL, Oracle, and SQL Server do not.
Look at orders:
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY,
customer_id INTEGER NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new',
total_amount NUMERIC(10, 2) NOT NULL,
CONSTRAINT pk_orders PRIMARY KEY (order_id),
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
ON DELETE RESTRICT,
CONSTRAINT ck_orders_total CHECK (total_amount >= 0),
CONSTRAINT ck_orders_status
CHECK (status IN ('new', 'paid', 'shipped', 'cancelled'))
);In PostgreSQL, orders.customer_id has no index. Two operations then become slow as the table grows:
- Deleting or updating a customer. The database must check whether any order still references that customer. With no index on
orders.customer_id, it scans all ofordersfor each such change. - Queries such as
SELECT * FROM orders WHERE customer_id = 42. This is a common access pattern, and it also scans the whole table.
The fix is an ordinary index that you create yourself:
CREATE INDEX ix_orders_customer_id ON orders (customer_id);This index is not a constraint. It enforces nothing. It only makes lookups on the child column fast.
Composite keys and column order
A composite key creates one index over several columns. The order of columns in that index matters. Consider the junction table:
CREATE TABLE order_items (
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id) REFERENCES orders (order_id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products (product_id)
);The primary key index is sorted by order_id first, then product_id. It serves these queries well:
WHERE order_id = 7WHERE order_id = 7 AND product_id = 3
It does not help a query that filters only on product_id, because the index is not sorted by that column first. A search such as "which orders contain product 3?", and the foreign key check when a product is deleted, would scan the table. If you need them, add a second index:
CREATE INDEX ix_order_items_product_id ON order_items (product_id);The foreign key on order_id needs no extra index in this table, because the primary key index already starts with order_id.
Constraint versus unique index
You can enforce uniqueness in two ways that look similar:
ALTER TABLE customers
ADD CONSTRAINT uq_customers_email UNIQUE (email);
CREATE UNIQUE INDEX ux_customers_email ON customers (email);Both reject duplicate emails, and both build a unique index underneath. The differences are in how the database treats them:
- A constraint is part of the table definition. It appears in the catalog as a constraint, and a foreign key can reference it.
- A plain unique index is an implementation detail. In PostgreSQL, a foreign key can reference a column covered by a unique index only if it is a real constraint or a non-partial unique index on those columns. Other systems vary.
- A unique index can have features that a constraint cannot, such as a
WHEREclause (a partial index) or an expression. For example, "email must be unique among active customers" needs a partial unique index in PostgreSQL.
Choose the constraint when the rule is part of the data model. Choose a unique index when you need those extra features.
NULL handling in unique indexes
Standard SQL allows multiple NULLs in a UNIQUE column, because NULL is not equal to another NULL. PostgreSQL, MySQL, and Oracle follow this. SQL Server treats NULLs as equal in a unique constraint, so it allows only one NULL row. PostgreSQL 15 and later adds UNIQUE NULLS NOT DISTINCT to choose the stricter behavior.
A primary key never has this issue, because it implies NOT NULL.
Costs of indexes
Every index speeds some reads and slows writes. Each INSERT, UPDATE, and DELETE must also update every index on the table. Constraint indexes are mandatory because the rule requires them. Extra indexes are your choice, so create them for a measured need:
- A foreign key you join or delete through.
- A column you filter on often.
Do not add an index on a column that duplicates the leading columns of an existing index. An index on (order_id) is redundant when the primary key already starts with order_id.
Dropping constraints and indexes
Dropping a constraint drops the index it owns:
ALTER TABLE customers DROP CONSTRAINT uq_customers_email;You cannot drop an index that backs a constraint with DROP INDEX. PostgreSQL rejects it with an error that says the index is required by the constraint. Drop the constraint instead. This is another case where names matter, because the constraint name is what you pass to DROP CONSTRAINT.
Adding a PRIMARY KEY or UNIQUE constraint to a large existing table builds an index, which can take time and lock the table for writes. Plan such changes for quiet periods, or look at your system's option for building indexes without blocking, such as PostgreSQL's CREATE UNIQUE INDEX CONCURRENTLY followed by ADD CONSTRAINT ... USING INDEX.
How a foreign key check uses indexes
The insert always uses the parent's primary key index, which exists. The delete uses the child's index, which exists only if you created it (or if you use MySQL).
Summary of rules
- PRIMARY KEY and UNIQUE create an index automatically.
- FOREIGN KEY does not create an index on the child column in most systems. Create one yourself.
- Composite indexes serve queries that use their leading columns.
- A constraint owns its index. Drop the constraint, not the index.
Exercise
In PostgreSQL, you have order_items (order_id, product_id, quantity) with PRIMARY KEY (order_id, product_id) and a foreign key from product_id to products. Deleting a product is slow on a large table. Why does it happen, and what statement fixes it?
Show answer
When a product is deleted, the database must check whether any orderitems row references it. The primary key index is sorted by orderid first, so it cannot find rows by productid alone, and the check scans the whole table. PostgreSQL does not create an index for a foreign key column. Create one with: CREATE INDEX ixorderitemsproductid ON orderitems (product_id);
Exercise
You run DROP INDEX on the index that PostgreSQL created for a UNIQUE constraint on customers.email. What happens, and what is the correct way to remove the index?
Show answer
PostgreSQL rejects the statement because the constraint requires the index. Drop the constraint with ALTER TABLE customers DROP CONSTRAINT constraint_name; the index is removed with it.