Sunday, March 10, 2013

SQL Table Joins

Print Friendly and PDF

A SQL JOIN combines data from two or more tables based on matching keys indicated in the SELECT statement. The matching keys are what creates the relationship between tables and uniquely identify the rows in a table.

INNER JOIN: This is the most common type of join and is considered the default join type. The inner join, sometimes referred to as an EQIJOIN, only brings back data that is a match between both tables being joined. In the example below:

SELECT statement states that we want all (*) columns from both tables.
FROM indicates the first table wanted.
INNER JOIN keyword specifies the other table we want to join to, the Orders table.
ON keyword is used in conjunction with the INNER JOIN keyword to indicate how the two tables are to be joined, in this example, the CustomerID of the Customers and Orders table. Customers.CustomerID and Orders.CustomerID is the format because the CustomerID name column is the same in both tables.


FROM Customers
On Customers.CustomerID = Orders. CustomerID

note: If you fail to indicate the relationship between the two tables, you will end up with a Cartesian product. A Cartesian product causes each row from the first table to be multiplied by the total number or rows from the second table.