Understanding Table Joins Using SQL - CodeProject
Understanding Table Joins Using SQL - CodeProject
home
articles
quick answers
discussions
features
community
help
Article Browse Code Stats Revisions (11) Alternatives Comments & Discussions (23)
About Article
Joins are useful for bringing data together from different tables based on their database relations. First we will see how the join operates between tables. Then we will explore the Order of Execution when Join and where condition both exists. Finally we will move our exploration to the Importance o Type Licence First Posted Views Downloads Article CPOL 6 Aug 2012 53,993 1,635 67 times
1. Introduction
Joins are useful for bringing data together from different tables based on their database relations. First we will see how the join operates between tables. Then we will explore the Order of Execution when Join and where condition both exists. Finally we will move our exploration to the Importance of the Join order.
Bookmarked
We are going to use these tables to perform the joins. These tables are just for demo purpose and So I do not have proper table relationship in terms of Primary and Foreign keys. OK, Let us move on.
www.codeproject.com/Articles/435694/Understanding-Table-Joins-using-SQL
1/10
12/4/13
Top News
Man throws away trove of Bitcoin worth $7.5 million
Get the Insider News free each morning.
Related Videos
Related Articles
Visual Representation of SQL Joins Difference between And clause along with on and Where clause when used with left join in SQL Server Creating SQL Joins in Simple Steps Understanding Set based and Procedural approaches in SQL SQL Joins Common Table Expressions(CTE) in SQL SERVER 2008 A scripted SQL query generation framework with IDE: SQLpp (v1.4) SQL Joins SQL Query Optimization FAQ Part 1 (With video explanation) Joining Tables in SQL Learn SQL to LINQ (Visual Representation)
Note that the Row Number 1 and Row number 5 are returned as the join result as they satisfies the mapping condition A.Id = B.Id. In the query it is shown in the Red Box.
SQL Tuning Tutorial Understanding a Database Execution Plan (1) Quick Overview: Temporary Tables in SQL Server 2005 Concatenate Field Values in One String Using CTE in SQL Server Database Virtual Cursor Get Tables List With Its Dependent Tables Names Three Really Handy Tricks With SQL Server Table Variables Sort Database Tables By Foreign Keys Database performance optimization part 2 (Index maintenance) Inside Recursive CTEs
Related Research
First Table_A is joins with Table_B, which is nothing but the previous example. Then the joint result of A and B is considered as single table say AB. Then the AB is joint with the Table_C . This is shown in the below
www.codeproject.com/Articles/435694/Understanding-Table-Joins-using-SQL
2/10
12/4/13
picture:
In-The-Wild Testing: How to Ensure Your Apps Work in the Real World
Protect Your Android App: Why Developers Should Leverage Secure Code Signing Certificates
6. Join Types
There are three type of join available based the way we join columns on two different tables. 1) Full outer Join 2) Inner Join 3) Left outer Join 4) Right outer Join What we saw in the previous two examples are the inner joins. If we join the same table we called it as Self join and it is special category do not get confuse it with the join types. Let us see an example for the join types in next coming examples.
Before we go into those examples, remember that the result computed so for is considered as LEFT and the new table coming to join the existing result is RIGHT. This is useful when we are joining multiple tables with different type of joins.
www.codeproject.com/Articles/435694/Understanding-Table-Joins-using-SQL
3/10
12/4/13
8. Left Join
Left join makes sure to take all the rows on the left side of the table by placing the null entries for the table joining on the right side when there is unmatched row on the right side.
In the above example, Id value of 2 in the Left table does not exist on the right side table Table_C.Id. But, we still got the 2,BBB row from the Table_A by placing the null entries for the right side table. This is shown in Green and red boxes above.
Also note that when SQL is processing, it takes the rows for the Table_A first (So Left) then joins it with the Table_C (Right side). It does not matter whether we provide A.Id = C.Id or C.Id = A.Id
9. Right Join
It is the reverse of the left join. It implies take all the rows on the right side of table by placing the null on the left table for unmatched rows. Below is the example for it:
Blue Box : Matched rows. Green : Row exits on the right side table Table_B and match (Based on Id column) not available on the left
Red : Null placement for the columns
www.codeproject.com/Articles/435694/Understanding-Table-Joins-using-SQL
4/10
12/4/13
Here, the row pointed by ReportTo column is Manager. So the table on the left hand side is employee and table on the Right hand side is Manager. When the FirstName is referred on the left table of the joint result, it is Employee name and the same FirstName on the right table of the join result is Manager name.
www.codeproject.com/Articles/435694/Understanding-Table-Joins-using-SQL
5/10
12/4/13
Option 1:
Option 2:
So keep in mind the operation sequence as SQL first completes the join first then applies the where clause when the query has one or more outer joins.
www.codeproject.com/Articles/435694/Understanding-Table-Joins-using-SQL
6/10
12/4/13
From the above query, you can see the order of join as mentioned below: 1) A right join between Orders and Customers. SQL first queries the Orders table (As it appears first) and treats the result as Left. Then it queries the Customers table next and treats the result set as Right. Finally from both the result set Right join is performed that means SQL ensures you that it will not lose any rows on the Right side result set that is it will not lose any rows from the Customers table. So you will get all customers including the two who dont placed any orders and since a matching records for those two rows are not available you will get null columns for the Orders. Now the resulting join result is available for the next join and this join result is now treated as Left.
2) Now the above returned result (Left side) is joint with the Order Details table. SQL knows it already has the Left result set so it query the table Order Details to have the Right. Finally an Inner join is performed between Left and Right based on the Order Id. But note that we have two null entries for the ordered column for which there are no corresponding customers in the Left side result. So the Inner join just skips those records. So we got a total of 2155 missing the two customers who does not place any orders, which is not the result we need. Read the Underlines text at the top of this section. Now look at the Query and Result below: [Inner Join then Outer Join]
Here, Inner join based on the OrderId between Orders and Order Details is performed first. This result (Left side) is
www.codeproject.com/Articles/435694/Understanding-Table-Joins-using-SQL
7/10
12/4/13
OK. Now let us see how this works and gives the expected result of not losing any customers. Note that the Rule remains same, whatever computed so for is Left and the Joining table is on the Right.
1) SQL first queries the table Customers and keeps it as the result on the Left. 2) It reads the Open parenthesis, and queries the table Orders and keeps it Left again. Why? SQL Says Boss, I know that I am not going to join this table and Table I am going join is not ready yet. So I kept is Left side result. 3) Now the Order Details table is queried and kept as Right side of join as Left side is already available.
4) A join between Order and Order Details is performed based on the Order Id. The resultant records are treated as right because the Customer table is already queried and kept in the Left. Now thee left join between the Left and Right side of result set brings all customers as the join type left outer join. Note: The scripts for creating the Demo tables and NorthWnd database is available as download.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
www.codeproject.com/Articles/435694/Understanding-Table-Joins-using-SQL
8/10
12/4/13
Sivaraman Dhamodharan
Software Developer iSOFT India I am working as software engineer in iSOFT R&D. I have been come accross C++,MFC, .net technologies. I do like playing video games, reading books. Web: DotNet
Programming Articles
Article Top
Join JOINS Counting Bug Joins in Sql My vote of 4 My vote of 5 My vote of 5 JOIN TWO TALBE and Show to DataGRIDVIEW Are you... Re: Are you...
Last Visit: 31-Dec-99 18:00 General News Last Update: 4-Dec-13 2:31 Suggestion Question Bug Answer
Member 10431234 Member 10353665 Bassam Abdul-Baki heemanshubhalla GregoryW RajeshMathew Brian A Stephens Navas Khanj Ravi Bhavnani sirama2004 Refresh Joke Rant Admin
27-Nov-13 20:33 8-Nov-13 5:41 24-Oct-13 5:28 19-Sep-13 0:16 24-Jul-13 1:20 23-Jul-13 13:37 8-Jul-13 2:16 24-Jan-13 8:50 15-Aug-12 18:45 15-Aug-12 19:17 1 2 3 Next
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
www.codeproject.com/Articles/435694/Understanding-Table-Joins-using-SQL
9/10
12/4/13
Permalink | Advertise | Privacy | Mobile Web03 | 2.7.131201.1 | Last Updated 22 Jul 2013
Article Copyright 2012 by Sivaraman Dhamodharan Everything else Copyright CodeProject, 1999-2013 Terms of Use
www.codeproject.com/Articles/435694/Understanding-Table-Joins-using-SQL
10/10