Arctus Blog: Learning SQL: Selecting from multiple tables using INNER JOIN tag:blog.arctus.co.uk,2005:Typo Typo 2007-04-20T07:28:42-04:00 Adrian O'Connor adrian@arctus.co.uk urn:uuid:356bfced-b433-42d3-98be-6785a7e436b9 2007-04-20T06:39:00-04:00 2007-04-20T07:28:42-04:00 Learning SQL: Selecting from multiple tables using INNER JOIN <p>Many years ago, when I started learning <span class="caps">SQL</span>, I used Microsoft&#8217;s documentation (because I was learning on <span class="caps">SQL</span> Server 6.5) and much of my early knowledge of <span class="caps">SQL</span> was based on their way of doing things.</p> <p>In the Microsoft documentation, nearly all of the examples used the short-hand notation for joins:</p> <pre>SELECT * FROM TableOne t1, TableTwo t2 WHERE t1.SomeKey = t2.Id AND t1.SomeValue = 'search'</pre> <p>I never really liked this, but I couldn&#8217;t quite explain why.</p> <p>It was only when I came across a &#8216;standards compliant&#8217; <span class="caps">ANSI SQL</span> tutorial that I realised that this was, in fact, completely the wrong way of doing it.</p> <p>Sadly, I still see lots of code being written this way. I recommend that all developers who are writing <span class="caps">SQL</span> code should force themselves to use the standards compliant syntax.</p> <p>The correct way is to use the key words <span class="caps">INNER JOIN</span>:</p> <pre>SELECT * FROM TableOne t1 INNER JOIN TableTwo t2 ON t1.SomeKey = t2.Id WHERE t1.SomeValue = 'search'</pre> <p>What you are saying is &#8220;join each row of TableTwo to the results in TableOne where the join criteria match.&#8221;</p> <p>It&#8217;s more verbose, but it is also much clearer. Clarity is a key feature of good programming style.</p> <p>The above example is only simple, but as your queries get more complex the benefits grow exponentially. Using the short-hand syntax, our <span class="caps">WHERE</span> clause is doing two jobs &#8211; it is joining our tables and filtering the results. By doing two jobs we are making it harder to read and harder to understand. With the <span class="caps">INNER JOIN</span>, our joins are explicity declared with the table that is being joined. The <span class="caps">WHERE</span> clause is filtering the records after all of the joins have completed.</p> <p>It is also worth noting that you must use the standard language for <span class="caps">LEFT OUTER</span> JOINs, a very powerful type of join.</p>