postgresqldatabase-designuniqueintegrity

Composite primary key better than unique index exclusion in PostgreSQL?


I am in the process of designing a database. I am taking my time to try to understand the key difference between using a unique index (using GIST EXCLUDE to enforce a specific business rule) and achieving the same result using a composite primary key.

In what case would it be proper to use a composite primary key to achieve uniqueness vs. using a unique index?


Solution

  • There is one notable difference between a primary key constraint and mere uniqueness: primary key columns have to be NOT NULL. The main purpose of a primary key is to ascertain that there cannot be two identical rows in a table. If the columns in your exclusion constraint are NOT NULL, and it truly excludes identical rows, it will serve that purpose just as well.

    There is one other difference between a primary key constraint and a unique exclusion constraint: the former can be referenced by a foreign key constraint, while the latter cannot. So I would say that you can safely go with only your exclusion constraint (provided it guarantees uniqueness), unless you need the columns to be the target of a foreign key constraint.