Lets say that I have a table where I want to record usernames. At minimum the table should have two columns : UserID and Name. Typically I see people put a primary key on UserID turn on auto increment and call it day.
However that seems wrong to me, shouldn’t the key be a composite key between both columns? As we don’t want the username to ever be repeated. We want to also keep UserID so that we don’t break existing references to a particular user if their name changes.
What I’m getting at is it seems like many people default to an ID column with a PK on it for every table they make without making sure that key enforces uniqueness on other columns as well.
With that being said, am I correct in stating that a table should always have an ID column for referencing, but it is equally important to use composite primary keys?
No, you don’t want it as a composite key; that means that the combination is the primary key, so you could then have different names on the same ID, and different ID’s on the same name.
I.E.:
In the absence of any other constraints, making the primary key a composite of
(UserID, Name)would make the previous data perfectly legal.Your
UserIDcolumn is a surrogate key; I’ll leave the discussion about the wisdom of using surrogate keys vs. natural keys (yourNamecolumn is a natural candidate key) for another time, but if you want to keep your design the way it is now, then you should leaveUserIDas the primary key but also add a unique constraint onName. This will prevent the same name from being attached to multiple records.