Sql-server – M:M Table Design – Use of PK

many-to-manyprimary-keysql serversurrogate-key

I have a many-to-many table that contains id's from 2 related tables.

For creating a primary key on this table, is it better to create another integer column and have that as a surrogate PK?

Or should I create the PK on both id columns?

What are the benefits of either method?

Here is the table design with the surrogate key (CodeGroupMappingID)

CREATE TABLE [dbo].[CodeGroupMappings](
    [CodeGroupMappingID] [int] IDENTITY(1,1) NOT NULL,
    [CodeID] [int] NOT NULL,
    [GroupID] [int] NOT NULL,
     CONSTRAINT [PK_CodeGroupMappings_CodeGroupMappingID] PRIMARY KEY CLUSTERED ([CodeGroupMappingID] ASC)
)

Best Answer

Here's the canonical design for a Many-to-Many linking table. You generally want an index to support traversal in each direction, and (at least for SQL Server) it doesn't matter whether you use a unique constraint, unique index or non-unique non-clustered index for the reverse key index: you end up with the same data structure.

CREATE TABLE CodeGroupMappings
(
    CodeID int NOT NULL,
    GroupID int NOT NULL,
    CONSTRAINT PK_CodeGroupMappings PRIMARY KEY CLUSTERED (CodeID, GroupID),
    CONSTRAINT AK_CodeGroupMappings UNIQUE (GroupID, CodeID),
    CONSTRAINT FK_CodeGroupMappings_Code FOREIGN KEY (CodeID) REFERENCES Code(CodeID),
    CONSTRAINT FK_CodeGroupMappings_Group FOREIGN KEY (GroupID) REFERENCES [Group](GroupID),
)