Problem solve Get help with specific problems with your technologies, process and projects.

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 || 
Where (division.course = section.course and division.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

For More Information

Or would it be better to do: Using the second example (comparing each column separately), you get three joined rows. Using the first example (comparing the concatenations), you get nine!

Dig Deeper on Oracle and SQL