Should a many to many table be indexed? What kind of index would be best?
Here's an example table:
CREATE TABLE user_role (
userId INT,
roleId INT
)
--edit: drachenstern - I added the table def based on the original comments, and assumed ints.
Should a many to many table be indexed? What kind of index would be best?
Here's an example table:
CREATE TABLE user_role (
userId INT,
roleId INT
)
--edit: drachenstern - I added the table def based on the original comments, and assumed ints.
You don't need a surrogate key (unless you use a braindead ORM) and you almost always need the 2nd index
In SQL Server, non-clustered indexes include the clustering key, so I would offer the following alternative solution based on the previous solution offered:
This is assuming that userid would be the more likely search/scan candidate.
If a query is run with a filter condition based on userid, then the clustered index would meet the needs; if a query is run with a filter condition based on roleid, the non-clustered index would cover the query; if a query uses both roleid and userid to filter then the clustered index would cover the query.
Please reference the following article information on how the clustering key is included in non-clustered indexes:
http://www.simple-talk.com/sql/learn-sql-server/effective-clustered-indexes/
Thanks, Jeff