Ask the Expert

Joining tables that have composite primary keys

When joining tables that have multiple fields making up the primary key, is it better to actually concatenate the fields together and then join, or to join on each individual field? For example, say I have a course management system that has a course table, division table and a section table. Course joins to division on course, and division joins to section on course and division.

So, is it better to do:

Where (division.course || division.division = section.course || 
Or would it be better to do:
Where (division.course = section.course and division.division = 

    Requires Free Membership to View

It is almost always better to use your second example. The concatenated columns can almost never use indices because most database engines don't support indexing expressions. The data comparison takes less time than just the concatenation does on most databases, and it almost certainly takes less time than the combination of concatenation followed by comparison!

Most importantly, concatenating the columns leads to possible comparison errors. Consider what happens when you have data in tables A and B that look like:

A.col1  A.col2  B.col1  B.col2

A          One      A          One
AO         ne          AO       ne
AOn      e         AOn     e
Using the second example (comparing each column separately), you get three joined rows. Using the first example (comparing the concatenations), you get nine!

For More Information

This was first published in December 2002

There are Comments. Add yours.

TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: