I have been wondering what the best practices or ramifications are in setting up the PK in a M2M table in SQL Server. For instance:
I have 2 tables
- Users
- Roles
I am making a new table
- UserRole
Which has 2 fields RoleId & UserID
now should I
- create a UserRoleID as the PK and make UserID and RoleID the FKs
- make the PK UserID AND RoleID and set them as FKs
- something else
I would like to know the performance issues with each of the options and what the recommended best practices are.
Standard procedure for these cases is to have two indexes. The unique PK is the two fields composite, with the field with the greater cardinality first, i.e. UserID; and the second index with just the secondary field (i.e. RoleID).
Then cluster on whichever is likely to be involved in more multirecord result sets (i.e. if querying for multiple roles per user, or multiple users per role).