Q

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 || 
section.division)
Or would it be better to do:
Where (division.course = section.course and division.division = 
section.division)

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

Dig deeper on Oracle and SQL

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

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:

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close