Sub topic 6
Composite Primary Keys
What a composite key guarantees
This chapter assumes you know basic SELECT, INSERT, UPDATE, and DELETE, can create tables, and understand rows, columns, and NULL.
A composite primary key is a primary key made from two or more columns. The database requires the combined value of those columns to be unique for every row. Each column in the key is also implicitly NOT NULL.
For example, an order can contain a product only once. The pair (order_id, product_id) identifies one product within one order:
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)
);The values in either column can repeat separately:
| order_id | product_id | quantity |
|---|---|---|
| 10 | 4 | 2 |
| 10 | 7 | 1 |
| 11 | 4 | 3 |
Here, product 4 appears in two orders, and order 10 contains two products. However, a second row with (10, 4) would violate the primary key.
Why use multiple columns?
Use a composite key when a row has no useful identity in one column and is naturally identified by a combination. Junction tables often use this design because each row represents a relationship between two parent rows.
A composite key also prevents duplicate relationships directly in the database. You do not need to rely only on application code to check for an existing pair.
Composite keys versus surrogate keys
A surrogate key is an artificial identifier, such as order_item_id. You could use one here and add a separate uniqueness rule:
CREATE TABLE order_items (
order_item_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
quantity INTEGER NOT NULL,
UNIQUE (order_id, product_id)
);The composite key expresses the business rule as the row identity. A surrogate key can make references simpler when other tables must refer to one line item. Choose based on how the row is referenced, not on a universal rule.
| Design | Main advantage | Main cost |
|---|---|---|
| Composite key | Directly represents the relationship | References must carry multiple columns |
| Surrogate key plus `UNIQUE` | Simple single-column references | Requires an additional uniqueness constraint |
Common mistakes
- Defining
PRIMARY KEY (order_id)in a junction table, which incorrectly allows each order to contain only one product. - Omitting one part of the key in joins or foreign-key references.
- Using nullable columns. Primary-key columns cannot be
NULL. - Assuming column order does not matter for indexes. An index on
(order_id, product_id)is most useful when queries filter byorder_idfirst.
Exercise
Which constraint prevents the same product from being added twice to order 12?
Show answer
PRIMARY KEY (order_id, product_id) prevents a second row with the pair (12, product_id).