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?
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:
int
to a numeric
-- you have to modify lots and lots of tables.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.