Why use multiple columns as primary keys (composite primary key)
Another example of compound primary keys are the usage of Association tables. Suppose you have a person table that contains a set of people and a group table that contains a set of groups. Now you want to create a many to many relationship on person and group. Meaning each person can belong to many groups. Here is what the table structure would look like using a compound primary key.
Create Table Person(
PersonID int Not Null,
FirstName varchar(50),
LastName varchar(50),
Constraint PK_Person PRIMARY KEY (PersonID))
Create Table Group (
GroupId int Not Null,
GroupName varchar(50),
Constraint PK_Group PRIMARY KEY (GroupId))
Create Table GroupMember (
GroupId int Not Null,
PersonId int Not Null,
CONSTRAINT FK_GroupMember_Group FOREIGN KEY (GroupId) References Group(GroupId),
CONSTRAINT FK_GroupMember_Person FOREIGN KEY (PersonId) References Person(PersonId),
CONSTRAINT PK_GroupMember PRIMARY KEY (GroupId, PersonID))
Your understanding is correct.
You would do this in many cases. One example is in a relationship like OrderHeader
and OrderDetail
. The PK in OrderHeader
might be OrderNumber
. The PK in OrderDetail
might be OrderNumber
AND LineNumber
. If it was either of those two, it would not be unique, but the combination of the two is guaranteed unique.
The alternative is to use a generated (non-intelligent) primary key, for example in this case OrderDetailId
. But then you would not always see the relationship as easily. Some folks prefer one way; some prefer the other way.