liveBook · Manning

Composite key

As explained in PostgreSQL Mistakes and How to Avoid Them

A composite unique key is a uniqueness rule defined over multiple columns whose combined values identify a row combination.

A composite unique key makes the combined values of several columns identify a row combination. In an inventory table, (product_id, warehouse_id, area) distinguishes stock records and lets an upsert update a matching row instead of inserting another. section 2.11

The NULL upsert trap

A unique index on (product_id, warehouse_id, area) behaves as expected for area = 'freezer': a second upsert updates quantity from 10 to 20. With area = NULL, PostgreSQL treats the repeated composite values as distinct, so quantities 5 and 7 become separate rows instead of one row being updated. Avoid nullable columns in composite unique keys when possible. section 2.8

PostgreSQL 15 and later can change this behavior with NULLS NOT DISTINCT. Recreate the unique index with that clause so matching NULL values participate in conflict detection and the upsert updates the existing row. section 2.8

How PostgreSQL Mistakes and How to Avoid Them covers it

How deep it goes
Explains ordinary and NULL-containing keys through executable inserts, table output, index recreation, and corrected upsert behavior.
Examples
Demonstrates warehouse inventory for product 99999 across freezer and NULL-area stock records.
What you can do after
Diagnose NULL-related duplicate upserts and configure NULLS NOT DISTINCT on PostgreSQL 15 or later.
How it connects
Connects composite unique keys with unique indexes, NULL semantics, and upserts using ON CONFLICT.

Also explained in

Compare how 8 books explain composite key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of PostgreSQL Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.