Design and best practice · Designing databases

Composite primary key

A composite primary key identifies each row by the combination of two or more columns.

Before continuing: This entry is part of the constraints and keys guide. If you are new to the topic, start with CREATE TABLE.

Composite primary key example

SQL
CREATE TABLE order_lines (
  order_id INTEGER NOT NULL,
  product_id INTEGER NOT NULL,
  quantity INTEGER NOT NULL CHECK (quantity > 0),
  PRIMARY KEY (order_id, product_id)
);

The constraint says the same order–product pair cannot repeat. Another order can contain the same product, and the same order can contain different products.

Test data
INSERT INTO order_lines VALUES (10, 2, 1);
INSERT INTO order_lines VALUES (10, 5, 2);
INSERT INTO order_lines VALUES (11, 2, 1);

Trying to insert another row with (10, 2) breaks the primary key because that combination already exists.

How a composite primary key is used

The constraint says the same order–product pair cannot repeat. Another order can contain the same product, and the same order can contain different products.

Differences and trade-offs

When to use one, and when to prefer a separate id

A composite key is a good fit when the combination is a natural, stable part of the data's identity. A separate surrogate id can be more practical when other tables will often need to reference the row, or when the columns in the combination may change.

Do not add a composite key just to “avoid duplicates” if the row already has another main identity: in that case a UNIQUE (column_a, column_b) constraint may express the rule better.

An important nuance in SQLite

The SQL standard and engines such as PostgreSQL treat the columns of a PRIMARY KEY as non-null. SQLite keeps a historical exception in ordinary rowid tables: certain primary keys that are not INTEGER PRIMARY KEY can accept NULL unless you declare NOT NULL, use a WITHOUT ROWID table or a STRICTtable. For portability and clarity, explicitly declare NOT NULL on the columns of a composite key when you work with SQLite.