SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.
Let's look at a selection from the "Orders" table:
OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
Then, look at a selection from the "Customers" table:
CustomerID CustomerName ContactName Country
1 Alfreds Futterkiste Maria Anders Germany
Ana Trujillo Emparedados y
2 Ana Trujillo Mexico
helados
Antonio
3 Antonio Moreno Taquería Mexico
Moreno
Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in
the "Customers" table. The relationship between the two tables above is the "CustomerID"
column.
Then, we can create the following SQL statement (that contains an INNER JOIN), that
selects records that have matching values in both tables:
EXAMPLE:
SELECT [Link], [Link], [Link]
FROM Orders
INNER JOIN Customers ON [Link]=[Link];
and it will produce something like this:
OrderID CustomerName OrderDate
10308 Ana Trujillo Emparedados y helados 9/18/1996
10365 Antonio Moreno Taquería 11/27/1996
10383 Around the Horn 12/16/1996
10355 Around the Horn 11/15/1996
10278 Berglunds snabbköp 8/12/1996
Different Types of SQL JOINs
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
records from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either left or
right table
Test Yourself With Exercises
Insert the missing parts in the JOIN clause to join the two tables Orders and Customers,
using the CustomerID field in both tables as the relationship between the two tables.
SELECT *
FROM Orders
LEFT JOIN Customers
__________ = __________ ;
SQL INNER JOIN Keyword
The INNER JOIN keyword selects records that have matching values in both tables.
INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
OrderID CustomerID EmployeeID OrderDate ShipperID
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
And a selection from the "Customers" table:
Custome CustomerNa Contact Postal
Address City Country
rID me Name Code
1 Alfreds Maria Obere Str.
Berlin 12209 Germany
Futterkiste Anders 57
Ana Trujillo Avda. de la
Ana México
2 Emparedados y Constitución 05021 Mexico
Trujillo D.F.
helados 2222
Antonio Moreno Antonio Mataderos México
3 05023 Mexico
Taquería Moreno 2312 D.F.
The following SQL statement selects all orders with customer information:
EXAMPLE:
SELECT [Link], [Link]
FROM Orders
INNER JOIN Customers ON [Link] = [Link];
Note: The INNER JOIN keyword selects all rows from both tables as long as
there is a match between the columns. If there are records in the "Orders" table
that do not have matches in "Customers", these orders will not be shown!
JOIN Three Tables
The following SQL statement selects all orders with customer and shipper information:
EXAMPLE:
SELECT [Link], [Link], [Link]
FROM ((Orders
INNER JOIN Customers ON [Link] = [Link])
INNER JOIN Shippers ON [Link] = [Link]);
Test Yourself With Exercises
Choose the correct JOIN clause to select all records from the two tables where
there is a match in both tables.
SELECT *
FROM Orders
__________
ON [Link]=[Link];
SQL LEFT JOIN Keyword
The LEFT JOIN keyword returns all records from the left table (table1), and the matched
records from the right table (table2). The result is NULL from the right side, if there is no
match.
LEFT JOIN Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
Customer Contact Postal
CustomerName Address City Country
ID Name Code
1 Alfreds Maria
Obere Str. 57 Berlin 12209 Germany
Futterkiste Anders
Ana Trujillo Avda. de la
Ana México
2 Emparedados y Constitución 05021 Mexico
Trujillo D.F.
helados 2222
Antonio Moreno Antonio Mataderos México
3 05023 Mexico
Taquería Moreno 2312 D.F.
And a selection from the "Orders" table:
OrderID CustomerID EmployeeID OrderDate ShipperID
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
SQL LEFT JOIN Example
The following SQL statement will select all customers, and any orders they might have:
EXAMPLE:
SELECT [Link], [Link]
FROM Customers
LEFT JOIN Orders ON [Link] = [Link]
ORDER BY [Link];
Note: The LEFT JOIN keyword returns all records from the left table (Customers), even if
there are no matches in the right table (Orders).
SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword returns all records from the right table (table2), and the
matched records from the left table (table1). The result is NULL from the left side, when
there is no match.
RIGHT JOIN Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Note: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
OrderID CustomerID EmployeeID OrderDate ShipperID
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
And a selection from the "Employees" table:
Employee
LastName FirstName BirthDate Photo
ID
1 Davolio Nancy 12/8/1968 [Link]
2 Fuller Andrew 2/19/1952 [Link]
3 Leverling Janet 8/30/1963 [Link]
SQL RIGHT JOIN Example
The following SQL statement will return all employees, and any orders they might have
placed:
EXAMPLE:
SELECT [Link], [Link], [Link]
FROM Orders
RIGHT JOIN Employees ON [Link] = [Link]
ORDER BY [Link];
Note: The RIGHT JOIN keyword returns all records from the right table (Employees), even
if there are no matches in the left table (Orders).
Test Yourself With Exercises
Choose the correct JOIN clause to select all the records from the Customers table plus all
the matches in the Orders table.
SELECT *
FROM Orders
__________
ON [Link]=[Link];
SQL FULL OUTER JOIN Keyword
The FULL OUTER JOIN keyword returns all records when there is a match in left (table1)
or right (table2) table records.
Note: FULL OUTER JOIN can potentially return very large result-sets!
Tip: FULL OUTER JOIN and FULL JOIN are the same.
FULL OUTER JOIN Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
Customer Customer Contact Postal
Address City Country
ID Name Name Code
1 Alfreds Maria
Obere Str. 57 Berlin 12209 Germany
Futterkiste Anders
Ana
Trujillo Avda. de la
Ana México
2 Emparedad Constitución 05021 Mexico
Trujillo D.F.
os y 2222
helados
Antonio
Antonio Mataderos México
3 Moreno 05023 Mexico
Moreno 2312 D.F.
Taquería
And a selection from the "Orders" table:
OrderID CustomerID EmployeeID OrderDate ShipperID
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
The following SQL statement selects all customers, and all orders:
EXAMPLE:
SELECT [Link], [Link]
FROM Customers
FULL OUTER JOIN Orders ON [Link]=[Link]
ORDER BY [Link];
A selection from the result set may look like this:
CustomerName OrderID
Alfreds Futterkiste Null
Ana Trujillo
10308
Emparedados y helados
Antonio Moreno Taquería 10365
Note: The FULL OUTER JOIN keyword returns all matching records from both tables
whether the other table matches or not. So, if there are rows in "Customers" that do not
have matches in "Orders", or if there are rows in "Orders" that do not have matches in
"Customers", those rows will be listed as well.
SQL Self JOIN
A self JOIN is a regular join, but the table is joined with itself.
Self JOIN Syntax
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
T1 and T2 are different table aliases for the same table.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Obere Str.
Maria Anders Berlin 12209 Germany
Futterkiste 57
Ana Trujillo Avda. de la
México
2 Emparedados y Ana Trujillo Constitución 05021 Mexico
D.F.
helados 2222
Antonio Moreno Antonio Mataderos México
3 05023 Mexico
Taquería Moreno 2312 D.F.
SQL Self JOIN Example
The following SQL statement matches customers that are from the same city:
SELECT [Link] AS CustomerName1,
[Link] AS CustomerName2, [Link]
FROM Customers A, Customers B
WHERE [Link] <> [Link]
AND [Link] = [Link]
ORDER BY [Link];
The SQL UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements.
Each SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in each SELECT statement must also be in the same order
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
UNION ALL Syntax
The UNION operator selects only distinct values by default. To allow duplicate values, use
UNION ALL:
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Note: The column names in the result-set are usually equal to the column names in the
first SELECT statement in the UNION.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Obere Str.
Maria Anders Berlin 12209 Germany
Futterkiste 57
Ana Trujillo Avda. de la
México
2 Emparedados y Ana Trujillo Constitución 05021 Mexico
D.F.
helados 2222
Antonio Moreno Antonio Mataderos México
3 05023 Mexico
Taquería Moreno 2312 D.F.
And a selection from the "Suppliers" table:
SupplierID SupplierName ContactName Address City PostalCode Country
49
Charlotte
1 Exotic Liquid Gilbert London EC1 4SD UK
Cooper
St.
P.O.
New Orleans New
2 Shelley Burke Box 70117 USA
Cajun Delights Orleans
78934
Grandma 707
Regina Ann
3 Kelly's Oxford 48104 USA
Murphy Arbor
Homestead Rd.
SQL UNION EXAMPLE
The following SQL statement returns the cities (only distinct values) from both the
"Customers" and the "Suppliers" table:
EXAMPLE:
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
Note: If some customers or suppliers have the same city, each city will only be listed
once, because UNION selects only distinct values. Use UNION ALL to also select duplicate
values!
SQL UNION ALL EXAMPLE
The following SQL statement returns the cities (duplicate values also) from both the
"Customers" and the "Suppliers" table:
EXAMPLE:
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
SQL UNION with WHERE EXAMPLE
The following SQL statement returns the German cities (only distinct values) from both
the "Customers" and the "Suppliers" table:
EXAMPLE:
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
ANOTER UNION EXAMPLE
The following SQL statement lists all customers and suppliers:
SELECT 'Customer' As Type, ContactName, City, Country
FROM Customers
UNION
SELECT 'Supplier', ContactName, City, Country
FROM Suppliers;
Notice the "AS Type" above - it is an alias. SQL Aliases are used to give a table or a
column a temporary name. An alias only exists for the duration of the query. So, here we
have created a temporary column named "Type", that list whether the contact person is a
"Customer" or a "Supplier".
The SQL GROUP BY Statement
The GROUP BY statement groups rows that have the same values into summary rows, like
"find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM,
AVG) to group the result-set by one or more columns.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Customer Contact
CustomerName Address City PostalCode Country
ID Name
1 Alfreds Maria
Obere Str. 57 Berlin 12209 Germany
Futterkiste Anders
Ana Trujillo Avda. de la
Ana México
2 Emparedados y Constitución 05021 Mexico
Trujillo D.F.
helados 2222
Antonio Moreno Antonio Mataderos México
3 05023 Mexico
Taquería Moreno 2312 D.F.
4 Thomas 120 Hanover
Around the Horn London WA1 1DP UK
Hardy Sq.
Berglunds Christina Berguvsvägen
5 Luleå S-958 22 Sweden
snabbköp Berglund 8
SQL GROUP BY Examples
The following SQL statement lists the number of customers in each country:
EXAMPLE:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
The following SQL statement lists the number of customers in each country, sorted high
to low:
EXAMPLE:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
OrderID CustomerID EmployeeID OrderDate ShipperID
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
And a selection from the "Shippers" table:
ShipperID ShipperName
1 Speedy Express
2 United Package
Federal
3
Shipping
GROUP BY With JOIN Example
The following SQL statement lists the number of orders sent by each shipper:
EXAMPLE:
SELECT [Link], COUNT([Link]) AS NumberOfOrders FROM
Orders
LEFT JOIN Shippers ON [Link] = [Link]
GROUP BY ShipperName;
Test Yourself with Exercises
List the number of customers in each country.
SELECT ___________ (CustomerID),
Country
FROM Customers
__________ ;