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 eUsing 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
- Dozens more answers to tough database design questions from Pat Phelan
- The Best Database Design Web Links: tips, tutorials, scripts, and more
- Have an Oracle or SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your database design questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
Related Q&A from Pat Phelan
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.