SQL Joins Explained: Simple Guide for Beginners

Shubham SourabhShubham Sourabh
10 min read

SQL Joins

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:

OrderIDCustomerIDOrderDate
1030821996-09-18
10309371996-09-19
10310771996-09-20

Then, look at a selection from the "Customers" table:

CustomerIDCustomerNameContactNameCountry
1Alfreds FutterkisteMaria AndersGermany
2Ana Trujillo Emparedados y heladosAna TrujilloMexico
3Antonio Moreno TaqueríaAntonio MorenoMexico

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:

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

Run🔗


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

SQL INNER JOIN

INNER JOIN

The INNER JOIN keyword selects records that have matching values in both tables.

Let's look at a selection of the Products table:

ProductIDProductNameCategoryIDPrice
1Chais118
2Chang119
3Aniseed Syrup210

And a selection of the Categories table:

CategoryIDCategoryNameDescription
1BeveragesSoft drinks, coffees, teas, beers, and ales
2CondimentsSweet and savory sauces, relishes, spreads, and seasonings
3ConfectionsDesserts, candies, and sweet breads

We will join the Products table with the Categories table, by using the CategoryID field from both tables:

Join Products and Categories with the INNER JOIN keyword:

SELECT ProductID, ProductName, CategoryName
FROM Products
INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID;

Syntax

SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;

Naming the Columns

It is a good practice to include the table name when specifying columns in the SQL statement.

SELECT Products.ProductID, Products.ProductName, Categories.CategoryName
FROM Products
INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID;

JOIN or INNER JOIN

JOINandINNER JOINwill return the same result.

INNER is the default join type for JOIN, so when you write JOIN the parser actually writes INNER JOIN.

SELECT Products.ProductID, Products.ProductName, Categories.CategoryName
FROM Products
JOIN Categories ON Products.CategoryID = Categories.CategoryID;

JOIN Three Tables

The following SQL statement selects all orders with customer and shipper information:

Here is the Shippers table:

ShipperIDShipperNamePhone
1Speedy Express(503) 555-9831
2United Package(503) 555-3199
3Federal Shipping(503) 555-9931
SELECT * FROM ((Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID) INNER JOIN Shippers ON Orders.ShippedID = Shippers.ShipperID);

SQL LEFT JOIN Keyword

The LEFT JOIN keyword returns all records from the left table (table1), and the matching records from the right table (table2). The result is 0 records 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.

SQL LEFT JOIN


Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico

And a selection from the "Orders" table:

OrderIDCustomerIDEmployeeIDOrderDateShipperID
10308271996-09-183
103093731996-09-191
103107781996-09-202

SQL LEFT JOIN Example

The following SQL statement will select all customers, and any orders they might have:

select * 
from customers
left join orders on customers.customerid = orders.customerid
order by customers.customername;

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 matching records from the left table (table1). The result is 0 records from the left side, if 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.

SQL RIGHT JOIN

Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Orders" table:

OrderIDCustomerIDEmployeeIDOrderDateShipperID
10308271996-09-183
103093731996-09-191
103107781996-09-202

And a selection from the "Employees" table:

EmployeeIDLastNameFirstNameBirthDatePhoto
1DavolioNancy12/8/1968EmpID1.pic
2FullerAndrew2/19/1952EmpID2.pic
3LeverlingJanet8/30/1963EmpID3.pic

SQL RIGHT JOIN Example

The following SQL statement will return all employees, and any orders they might have placed:

select *
from orders
right join employees
on employees.employeeid = orders.employee.id
order by orders.orderid;

Note: The RIGHT JOIN keyword returns all records from the right table (Employees), even if there are no matches in the left table (Orders).

SQL FULL OUTER JOIN Keyword

A FULL OUTER JOIN is a type of join operation in SQL that combines the results of both a LEFT JOIN and a RIGHT JOIN. It returns all rows from both tables involved in the join, regardless of whether a match exists between them

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;

SQL FULL OUTER JOIN

Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico

And a selection from the "Orders" table:

OrderIDCustomerIDEmployeeIDOrderDateShipperID
10308271996-09-183
103093731996-09-191
103107781996-09-202

SQL FULL OUTER JOIN Example

select *
from customers
full outer join orders
on customers.customerid = orders.customerid
order by orders.orderid;

A selection from the result set may look like this:

CustomerNameOrderID
Null10309
Null10310
Alfreds FutterkisteNull
Ana Trujillo Emparedados y helados10308
Antonio Moreno TaqueríaNull

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

🔗Self Join Explained Well - Click Here!

A self join is a regular join, but the table is joined with itself.

Suppose an organization, while organizing a Christmas party, is choosing a Secret Santa among its employees based on some colors. It is designed to be done by assigning one color to each of its employees and having them pick a color from the pool of various colors. In the end, they will become the Secret Santa of an employee this color is assigned to.

As we can see in the figure below, the information regarding the colors assigned and a color each employee picked is entered into a table. The table is joined to itself using self join over the color columns to match employees with their Secret Santa.

Self Join Syntax

SELECT columns
FROM table AS alias1
JOIN table AS alias2 ON alias1.column = alias2.column;

Self Join

Example -
👩‍💻Env to perform this query 🎯

--Create TB
CREATE TABLE People (
  Color_belongs VARCHAR(50),
    Name VARCHAR(50),
    Color_assigned VARCHAR(50)
);
--Insert data
INSERT INTO People (Color_belongs , Name , Color_assigned ) VALUES
('Blue', 'John', 'Red'),
('Green', 'Alex', 'Blue'),
('Red', 'Simon', 'Green');
-- Self Join query -
SELECT 
    p1.Name AS Person,
    p2.Name AS Secret_Santa
FROM 
    People p1, people p2
where p1.Color_assigned = p2.Color_belongs  ;

-- we can use this query for self join too 
SELECT p1.Name AS Person,p2.Name AS Secret_Santa
FROM People p1
join people p2 on p1.Color_assigned = p2.Color_belongs  ;

〽ALT Syntax -

SELECT column_name(s)
FROM table1 a, table1 b
WHERE a.common_field = b.common_field;

Note - Unlike queries of other joins, we use WHERE clause to specify the condition for the table to combine with itself; instead of the ON clause.

Example

Self Join only requires one table, so, let us create a CUSTOMERS table containing the customer details like their names, age, address and the salary they earn.

CREATE TABLE CUSTOMERS (
   ID INT NOT NULL,
   NAME VARCHAR (20) NOT NULL,
   AGE INT NOT NULL,
   ADDRESS CHAR (25),
   SALARY DECIMAL (18, 2),       
   PRIMARY KEY (ID)
);

Edit & Run🔗

Now, insert values into this table using the INSERT statement as follows

INSERT INTO CUSTOMERS VALUES
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),
(2, 'Khilan', 25, 'Delhi', 1500.00 ),
(3, 'Kaushik', 23, 'Kota', 2000.00 ),
(4, 'Chaitali', 25, 'Mumbai', 6500.00 ),
(5, 'Hardik', 27, 'Bhopal', 8500.00 ),
(6, 'Komal', 22, 'Hyderabad', 4500.00 ),
(7, 'Muffy', 24, 'Indore', 10000.00 );

Now, let us join this table using the following Self Join query. Our aim is to establish a relationship among the said Customers on the basis of their earnings. We are doing this with the help of the WHERE clause.

SELECT a.ID, b.NAME as EARNS_HIGHER, a.NAME 
as EARNS_LESS, a.SALARY as LOWER_SALARY
FROM CUSTOMERS a, CUSTOMERS b
WHERE a.SALARY < b.SALARY;

Output

The resultant table displayed will list out all the customers that earn lesser than other customers −

IDEARNS_HIGHEREARNS_LESSLOWER_SALARY
2RameshKhilan1500.00
2KaushikKhilan1500.00
6ChaitaliKomal4500.00
3ChaitaliKaushik2000.00
2ChaitaliKhilan1500.00

Self Join with ORDER BY Clause

After joining a table with itself using self join, the records in the combined table can also be sorted in an order, using the ORDER BY clause.

Syntax

Following is the syntax for it −

SELECT column_name(s)
FROM table1 a, table1 b
WHERE a.common_field = b.common_field
ORDER BY column_name;
10
Subscribe to my newsletter

Read articles from Shubham Sourabh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shubham Sourabh
Shubham Sourabh

Sipping lattes, diving into Linux, conquering Leetcode, and Lifting spirits (and weights) along the way! 🚀