|
How does a join work?One of the fundamental challenges in understanding SQL is becoming comfortable with thinking about data in terms of mathematical sets and relational algebra. This is the similar to the challenge procedural programmers face when making the transition to object-oriented languages -- things are just simply different and the old rules simply don't apply. Joins force you to think in a set-oriented way. That is one of the reasons why they are one of the most difficult parts of SQL to learn. So what actually happens when a join is executed? We can start with the simplest possible join -- the "cross join" (or Cartesian product). If we have two database tables consisting of information about CDs and musical artists:
A join simply multiplies the two tables together into a new virtual table. There are four members of the Artists table and seven members in the CDs table which will result in 28 (!) rows in the result. You can try this using the following syntax,
and you should see a result that looks like the following table:
This table is typically filtered using the
which leads us to another nugget of SQL wisdom SQL Wisdom #6) Using a cross join is almost always a bad idea A cross join will typically bring your database to its knees since the amount of work increases as a multiple of the number of rows -- this does not scale linearly! Other types of JOINsWe've covered two types of joins so far, but there are many more. To whet you appetite for the upcoming columns, the major types of joins we'll cover include
The world of joins is another one of those pleasant corners of the SQL world where there is a lot of differentiation between database platforms as far as specific syntax and even which types of joins are supported. We'll cover the big picture for each type of join, but will only point out an whopping differences between the platforms. It is crucial when you are working with any complicated join, particularly one that involves multiple tables or nested joins, that you check you DBMS documentation to make sure that your approach is supported.
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||