For example I have 2 tables, Users
and UserRelations
, and it is a one to many relationship.
For the UserRelations
table, I can have an identity column and make it the primary key:
[RelationID] [int] IDENTITY(1,1) NOT NULL,
[UserID] [int] NOT NULL,
[TargetID] [int] NOT NULL,
Or I can design the table like:
[UserID] [int] NOT NULL,
[TargetID] [int] NOT NULL,
and make UserID
+ TargetID
the primary key.
My question is what are the implications of going with each design, which is better for performance?
We can set PRIMARY KEY constraint on multiple columns of an existing table by using ADD keyword along with ALTER TABLE statement.
In Table Designer, click the row selector for the database column you want to define as the primary key. If you want to select multiple columns, hold down the CTRL key while you click the row selectors for the other columns. Right-click the row selector for the column and select Set Primary Key.
Yes, we can have more than one column as primary key to solve some business requirements. Primary Keys ensures that the column(s) will not have duplicate values , Null in the table.
Sometimes it requires more than one attribute to uniquely identify an entity. A primary key that made up of more than one attribute is known as a composite key.
If you use the former design, with the superfluous identity column, there's no constraint against inserting two rows with identical UserID and TargetID. You'd have to create a UNIQUE
constraint over the other two columns, which creates a compound index anyway.
On the other hand, some frameworks (e.g. Rails) insist that every table has a surrogate key named id
so the "correct" design may not work. It depends on what code you're writing to use this table design.
This is almost a religious issue. For each person who says use a non-intelligent surrogate key, somebody else points outs that surrogate keys can be considered superfluous, etc, etc. So do whatever feels most comfortable for you and your team.
If you do decide to use a surrogate key, you should also put a unique constraint on the natural (in this case multi-column) key, to keep the integrity of your data.
I usually go for an additional surrogate key, as there are a number of desirable (not necessarily required) primary key characteristics that natural keys sometimes lack:
From a performance point of view, I suspect there is little difference in most cases. But as with any performance issue, you should measure where you have concerns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With