Composite keys in M:N relationship tables

Composite keys in M:N relationship tables

What is the general procedure for dealing with M:N relationships encountered during the process of database design? Are composite keys always a straightforward solution?

    Requires Free Membership to View

    By submitting your registration information to SearchOracle.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchOracle.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

There is so much to be said on this subject, it's hard to decide where to start. Let's look at a simple example.

create table users
( id    smallint not null primary key 
, name  varchar(9)
)
create table projects
( id    smallint not null primary key 
, name  varchar(9)
)
create table userprojects
( userid  smallint not null 
, projectid smallint not null 
, projectrole varchar(15) 
, primary key (userid,projectid)
, foreign key (userid) 
    references users (id)
, foreign key (projectid) 
    references projects (id)
)

This is the same example used in another recent SQL answer, Inserting and searching many-to-many relationships.

Note that the relationship table USERPROJECTS has a composite key. Is this a straightforward solution? Yes. Is this the recommended way? Yes. Many database developers will automatically give this table a separate surrogate key (i.e. SEQUENCE, IDENTITY, AUTO_INCREMENT, etc.), but I do not.

The only time it makes sense to use a surrogate key is when the relationship table itself has child tables, and the child tables have many rows, and the queries using the child tables are complex. Relationship tables with child tables do occur, but they are rare. Unless you have a compelling reason, use composite keys.

And if you do decide to use a surrogate key for the relationship table, don't forget to declare a unique constraint on the composite anyway.

For More Information


This was first published in June 2004

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.