Sub topic 6
Composite primary keys
This chapter assumes you can write CREATE TABLE statements, know the basic constraints NOT NULL and UNIQUE, and have seen a single-column primary key. Examples use PostgreSQL syntax.
What a composite key is
A composite primary key is a primary key made of two or more columns. The database guarantees that the combination of values is unique and that none of the columns is NULL. Each column on its own may repeat freely.
The constraint is one rule applied to the whole column list. It is not a separate rule per column. In PRIMARY KEY (order_id, product_id), the value order_id = 1 can appear many times, and so can product_id = 5. Only the pair (1, 5) is limited to one row.
When a composite key fits
A composite key fits when a row is identified by the combination of two things and has no identity of its own. Typical cases:
- A junction table that resolves a many-to-many relationship, such as which products appear in which orders.
- A child row whose identity depends on its parent, such as line number 3 within order 17.
- A time-series row identified by a sensor and a timestamp.
Defining a composite key
A composite key must be declared as a table constraint, after the column definitions. Column-level PRIMARY KEY works only for one column.
CREATE TABLE products (
product_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
ordered_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
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) ON DELETE RESTRICT
);Here order_items has no item_id column. The pair (order_id, product_id) identifies each row, so a given product can appear at most once per order. To buy more of it, you raise quantity.
The next block inserts rows and shows which ones are rejected.
INSERT INTO customers (email, name) VALUES ('[email protected]', 'Ana');
INSERT INTO products (name) VALUES ('Keyboard'), ('Mouse');
INSERT INTO orders (customer_id) VALUES (1);
INSERT INTO order_items (order_id, product_id, quantity) VALUES (1, 1, 2);
INSERT INTO order_items (order_id, product_id, quantity) VALUES (1, 2, 1);
-- Fails: the pair (1, 1) already exists
INSERT INTO order_items (order_id, product_id, quantity) VALUES (1, 1, 5);The first two inserts succeed, even though order_id repeats. The third fails with a unique violation on the primary key.
How the pieces work together
Each column of a composite key is implicitly NOT NULL. Writing NOT NULL explicitly, as above, is harmless and makes the intent obvious when someone reads the table definition.
The database builds one unique index over the whole column list. This has a consequence for queries, covered in the next section.
Column order matters
The unique index behind PRIMARY KEY (order_id, product_id) is sorted by order_id first, then by product_id within each order. A B-tree index (the default index type in most databases) can be used efficiently only from its leftmost column onward.
| Query filter | Uses the primary key index efficiently? |
|---|---|
| `WHERE order_id = 1` | Yes, leftmost column |
| `WHERE order_id = 1 AND product_id = 2` | Yes, both columns |
| `WHERE product_id = 2` | Usually no, leftmost column is missing |
If you often look up rows by product_id alone, add a separate index for it.
CREATE INDEX idx_order_items_product_id ON order_items (product_id);As a rule of thumb, put first the column you filter on most often by itself. For a child table, that is usually the parent's key.
Foreign keys that reference a composite key
A foreign key can point to a composite primary key. It must then list all the columns, in matching order, and the referenced columns must be a primary key or unique constraint.
CREATE TABLE order_item_notes (
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
note TEXT NOT NULL,
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id, product_id)
REFERENCES order_items (order_id, product_id)
ON DELETE CASCADE
);This is one foreign key over two columns, not two separate foreign keys. A note row is valid only if the exact pair exists in order_items. Wide composite keys get copied into every child table, which makes the schema heavier. That is one reason many designs give such tables a surrogate key instead.
Composite key or surrogate key
You can also give a junction table its own generated key and enforce uniqueness of the pair separately.
CREATE TABLE order_items_v2 (
order_item_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id INTEGER NOT NULL REFERENCES orders (order_id) ON DELETE CASCADE,
product_id INTEGER NOT NULL REFERENCES products (product_id),
quantity INTEGER NOT NULL CHECK (quantity > 0),
UNIQUE (order_id, product_id)
);| Consideration | Composite key | Surrogate key plus UNIQUE |
|---|---|---|
| Number of columns and indexes | Fewer, one index | An extra column and an extra index |
| Child tables that reference it | Must copy every key column | Copy one column |
| ORM and framework support | Sometimes awkward | Usually simple |
| Rows may repeat the pair | No | No, if you keep the `UNIQUE` constraint |
Leaving out the UNIQUE constraint is the most common mistake with the surrogate version. Without it, the same product can be added to an order twice, and the database does not object.
Edge cases and gotchas
- Updating a key column. Changing
order_idorproduct_idchanges the row's identity. Any child rows must be handled by anON UPDATEaction, or the update fails. Composite keys made of values that never change avoid this. - No partial uniqueness. The pair is unique, but the individual columns are not. Do not add
UNIQUEon a single column of the key unless you really want only one row per value. - NULL is never allowed. Optional parts cannot be in the key. If one component can be missing, use a surrogate key and a different uniqueness rule.
- Key bloat. Every extra column enlarges the primary key index and every foreign key copy of it. Keep composite keys short, usually two or three columns.
- Redundant columns. Do not include a column that is already determined by the others. A key
(order_id, product_id, customer_id)is wrong ifcustomer_idfollows fromorder_id.
Exercises
Exercise
A table enrollments links students to courses. Write a CREATE TABLE statement so that a student can enroll in a course only once, and explain which query on this table would not benefit from the primary key index.
Show answer
CREATE TABLE enrollments (studentid INTEGER NOT NULL REFERENCES students (studentid), courseid INTEGER NOT NULL REFERENCES courses (courseid), enrolledon DATE NOT NULL DEFAULT CURRENTDATE, PRIMARY KEY (studentid, courseid)); The pair is unique, so a repeat enrollment fails. The index is sorted by studentid first, so a query that filters only on courseid, such as WHERE courseid = 7, cannot use it efficiently. Add CREATE INDEX idxenrollmentscourseid ON enrollments (course_id) if that query is common.
Exercise
Given PRIMARY KEY (orderid, productid) on order_items, which of these inserts fail, assuming the referenced parent rows exist and the table is empty before the first one: (1, 1), (1, 2), (2, 1), (1, 1), (NULL, 3)?
Show answer
The fourth, (1, 1), fails because the pair already exists. The fifth, (NULL, 3), fails because a primary key column cannot be NULL. The first three succeed: repeating orderid or productid alone is allowed, only the full pair must be unique.