Search code examples
sqldatabasepostgresqldatabase-schema

Why Composite Primary key when I can use Single Primary key with Unique constraints on composite columns?


I am in a situation where I am thinking of changing my tables schemas from a single primary key to a composite primary key.

This change will affect many of my tables and the SQL statements (Especially join queries) written to query such tables.

Having done some research on the benefits of the composite key approach, I found one major selling point is it's use to enforce uniqueness of the composite columns.

However, I can still leave my single primary key tables and then add a unique constraints to enforce uniqueness on the composite columns like this:

create table ... (
 id primary key not null,
 column1 ...
 column2 ...
 .
 .
 columnN ...
 unique(column1, column2) // added this line to my existing tables
)

Now to the questions:

What are the benefits of either approaches?

Explicitly defining a composite primary key or using a single primary key with unique constraints on the composite columns. Why?


Solution

  • You do not need a primary key to enforce uniqueness. You can use a unique constraint or index instead.

    I am not a fan of composite primary keys. Here are some reasons:

    • All foreign key references have to include all the keys in the correct order and matching types. This makes is slightly more cumbersome to define those tables.
    • Because the composite keys are included in all referencing tables, those tables are often larger, which results in worse performance.
    • If you decide that you want to change the type of one of the component keys -- say the length of a string or an int to a numeric -- you have to modify lots and lots of tables.
    • When joining tables, you have to include all the keys. If you miss one . . . well, the code is syntactically correct but the results are wrong.

    There are occasions where composite keys are acceptable, such as tables that have no foreign key references. Even in those cases, I use synthetic keys, but I totally understand the other perspective.