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?
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
UNIQUEconstraint 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
idso the ‘correct’ design may not work. It depends on what code you’re writing to use this table design.