time to read 5 min read

SQL Joins: What They are, How They Work, and How Many Types Exist

Did you ever need to Join two tables? An SQL Join statement lets you access data from multiple sources – tables in SQL.  

You might ask, What is SQL?” or/and “What are SQL joins?” depending on how far down you are on the SQL path, And we’d say that’s a fair question. While it’s a very well-known acronym, it is an important part of database management systems (DBMS). SQL manages everything from giant corporate databases to small local databases. 

Think of it like this; if we have to write code and programs for each type of data because there aren’t any specialized tools to help us do this, we will drown in data clutter. If you’re creating web pages or sending emails and there are millions of different options available, you want something that will make all that information easier to read and work with — not harder! That’s what SQL does for you. 

SQL (Structured Query Language) manages data in relational database management systems (RDBMS). A developer who knows SQL can write code to create, modify, and retrieve data stored in a database.

SQL is the most widely used database language in the world. It’s an essential skill for anyone working with websites or applications that use databases to store information.

In addition to using SQL commands directly, most database applications allow you to enter SQL statements through graphical user interfaces or wizards.

In this blog post, we’ll discuss SQL joins with examples to show how you can use this technique to improve your queries.

Types of SQL Joins

SQL selects the data Join from two tables (or more) based on the same key data points  between them; the top 4 types of SQL join statements are as follows: 

  1. Cross Join

A cross-join is a Cartesian product of two or more tables. A cross-join can combine data from multiple tables into a single result set. For example, if you have a table named Employees that contains employee names and phone numbers, you can cross-join with another table named Phones to get each employee’s phone numbers.

The syntax for a cross-join is as follows:

SELECT * FROM [table name 1] CROSS JOIN [table name 2]

Take a look at the clear cross-join example below.

Table 1: Car_model

Car_model
1Corolla
2Cultus
3Camry

Table 2: Color_name

Color_name
1Black
2Silver
3Red

To get all possible combinations of cars and colors, you need to execute the following piece of code:

SELECT
c.Car_model
,c1.Color_name
FROM Cars c
CROSS JOIN Colors c1

This will generate a Cartesian product of all possible values of above 2 tables.

Car_modelColor_name
1CorollaBlack
2CultusBlack
3CamryBlack
4CorollaSilver
5CultusSilver
6CamrySilver
7CorollaGrey
8CultusGrey
9CamryGrey
  1. Inner Join

An inner join is a type of join that joins two tables based on the matching values in their columns. The result of the inner join contains all rows from both tables, with matching rows from both tables linked together.

To use an inner join in SQL, you use the following syntax:

SELECT * FROM table1 INNER JOIN table2 

ON table1.column_name = table2.column_name; 

Here’s how this code works:

Table 1: Foods

ITEM_ID ITEM_NAMEITEM_UNITCOMPANY_ID
1Cheeze MixPcs16
6Cheeze ItPcs15
2BiscuitsPcs15
3MunchPcs17

Table 2: Company

COMPANY_IDCOMPANY_NAMECOMPANY_CITY
18NestleLondon
15Jack FoodsBoston
16FoodiesAmerica
17Akas FoodAustralia

You need to execute following piece of code to get the desired outcome with Inner join:

SELECT foods.item_name,foods.item_unit, company.company_name,company.company_city FROM foods INNER JOIN company ON foods.company_id =company.company_id;

You’ll get the following output:

ITEM_NAMEITEM_UNITCOMPANY_NAMECOMPANY_CITY
Cheeze MixPcsNestleLondon
Cheeze ItPcsJack FoodsBoston
BiscuitsPcsFoodiesAmerica
MunchPcsAkas FoodAustralia
  1. Self Join

Self-join enables the joining of a table to itself. To employ a self join, the table must contain a column (let’s call it X) that serves as the primary key and another column (let’s call it Y) that includes values that can be matched up with the values in Column X. 

Columns X and Y do not need to have identical values for any given row, and Column Y can even be null.

Here is an illustration of the members and their administration. Let’s examine the membership table:

Each member has a unique identifier, which we refer to as “Column X.” The Teamlead Id column contains the member or teamleader’s Id; this is our “Column Y.” If these columns are utilized to monitor the member-teamleader relationships in this table:

Table: Customers

Id FullNameSalaryTeamleadId
1Chirs Hemsworth2000005
2Tom Holland2500005
3Ben Affleck1200001

You need to execute following piece of code:

SELECT
    member. Id,
        member.FullName,
        member.teamleadId,
        teamlead.FullName as teamleadName
FROM members member
JOIN members teamlead
ON member.teamleadId = teamlead.Id

This will show you the following output:

IdFullNameTeamlead IdTeamlead Name
1Chirs Hemsworth5Gal Galdot
2Tom Holland5Gal Galdot
3Ben Affleck1Chirs Hemsworth
5Gal Galdot4Christian Bale
  1. Outer Join

An outer join returns matching and non-matching values from one or both tables.

Outer joins subdivide additionally into three subcategories:

  1. Left outer join
  2. Right outer join
  3. Full outer join 

These categories depend on the table’s rows included: left, right, and both. Assume an example of Pets table and Owner table for all these Outer join types.

Table 1: Pets

IDPet.NameOwner.ID
1Neiger1
2Bella2
3Snowie2
4Tiger3
5Swiky0

Table 2: Owers

IDOwner.Name
1Stephan
2Jonny
3Charlie
4Vicky
  • Left Outer Join

A left outer join is a way to join two tables together. Only rows from the table named before the LEFT OUTER JOIN clause that was not found in the target table are included in the output.

SELECT pets.name AS pet_name, owners.name AS owner
FROM pets
LEFT JOIN owners
ON pets.owner_id = owners.id;

You’ll get it as:

Pet.nameOwner
NeigerStephan
BellaJonny
SnowieJonny
TigerCharlie
SwikyNULL
  • Right Outer Join

A right join (or outer join) is like the left outer join, except with the reversed table treatment. 

Let’s do the same query with right join:

SELECT pets.name AS pet_name, owners.name AS owner
FROM pets
RIGHT JOIN owners
ON pets.owner_id = owners.id;

In this case, we retain all relevant rows from the owner’s table, and if any columns from pets require values but don’t have any, we substitute NULL.

Pet.nameOwner
NeigerStephan
BellaJonny
SnowieJonny
TigerCharlie
NullVicky
  • Full Outer Join

This category (full outer join) combines the applying effect of both left and right (outer joins). 

There is no match in the full outer joined table rows; it appears that it will consider the result set to have NULL values for every table’s column that lacks a matching row. 

A single row will produce the result for those (rows) that have some matching possibilities.

Here’s the query for this:

SELECT pets.name AS pet_name, owners.name AS owner
FROM pets
FULL JOIN owners
ON pets.owner_id = owners.id;

It will produce the following results:

Pet.nameOwner
NeigerStephan
BellaJonny
SnowieJonny
TigerCharlie
SwikyNull
NullVicky

How to Select Data from Multiple Tables Using SQL Joins?

You can get information from as many tables as you want, specify the conditions based on any data in the tables, and display the results in any order you choose if your database is properly designed and linked.

Let’s have an example:

Table 1: Product

IDNamePriceCategory_ID
1Table2002
2Chair1203
3Bricks1502
4Sofa501
5Sand201
6Toy Car1002

Table 2: Category

IDCategory
1Material
2Furniture
3Toys

You need following code to get the desired outcome:

SELECT
  product.name AS product_name,
  category.name AS category_name
FROM product
JOIN category ON product.category_id=category.id;

After execution, you’ll get following output:

Product_nameCategory
TableFurniture
ChairFurniture
BricksMaterial
SofaFurniture
SandMaterial
Toy CarToys

Use Cases for SQL Joins

The basic application of SQL Joins is to select data from many tables, as shown above. But, it can be applied to address different tasks. Some of the most occurring usage scenarios for SQL joins are:

  • Relationship Hierarchy: Joins are used if a multi-tiered relationship exists among tables, e.g., grandfather, father, son relationship or user, city, and state relationship.
  • Many-to-many Connections: This scenario occurs when many items in one table have a relationship with many items in the second table. For example, students are enrolled in multiple courses, and courses are assigned to multiple students. Same as customers subscribe to different products while products are shared by customers.
  • SQL Joins for Data Analysis: From a business intelligence (BI) perspective, SQL joins analyze data for making charts and building dashboards.
  • Database Normalization: In normalization, larger tables are organized into smaller tables to drop any data redundancy and anomalies. Then relevant data is fetched from these smaller tables using SQL joins. 

Learn SQL Joins with Sololearn

AS a declarative language, SQL needs joins statements to extract relevant data from highly structured databases.  . They can be confusing, especially if you’re new to SQL, but they are worth learning. We have given you different commands to help you write queries and recreate them around your databases. So, to learn more SQL join or relational databases, you must start with a basic beginner program. 

All three-course levels (beginners, intermediate, and compiler) at Sololearn will provide you with the complete coverage of SQL joins, their importance, and easy ways to imply them daily.