SQL JOINS: A Guide to Left, Right, Inner, and Full Outer Joins

Brandon Wohlwend
13 min readAug 2, 2023

--

Introduction

In the symphony of data exploration, we have embarked on a journey of SQL mastery, traversing the landscapes of fundamental statements and the harmonious melodies of aggregating functions and grouping. Our previous articles have revealed the magic of SELECT, FROM, WHERE, INSERT INTO, DELETE, and UPDATE statements, guiding us in querying, manipulating, and managing data with finesse.

Having gained proficiency in the SQL language, we now stand on the precipice of a new chapter in our data odyssey: the art of uniting data with SQL JOINS. In this article, we shall uncover the secrets of LEFT JOIN, RIGHT JOIN, INNER JOIN, and FULL OUTER JOIN, mastering the art of combining data from multiple tables in perfect harmony.

Drawing upon the knowledge and practices from our previous articles, we shall explore how JOINS act as the instrumental ensemble, bringing disparate datasets together to create a symphony of insights. As we unite data from various sources, we shall showcase the power and versatility of each JOIN type, unraveling their unique roles in data analysis scenarios.

Join us as we step into a world where data harmonizes, information resonates, and insights crescendo. Let us elevate our SQL expertise, unravel the mysteries of JOINS, and craft data symphonies that resonate with brilliance and elegance.

2. Understanding the Basics of JOINS

In the grand orchestra of SQL, JOINS take center stage as the maestros of data combination, orchestrating the union of information from different tables. Understanding the concept of JOINS is akin to unlocking the secret to uniting datasets that share common columns, bringing harmony to our data symphony.

Concept of JOINS in SQL and How They Enable Combining Data from Different Tables Based on Common Columns

JOINS in SQL are the powerful instruments that allow us to combine data from multiple tables into a single, cohesive result set. When our data is spread across various tables, each containing pieces of the puzzle, JOINS act as the glue that binds them together based on common columns.

To perform a JOIN, we identify the shared columns, known as the join key, between two or more tables. By using this join key, SQL matches rows with corresponding values, effectively merging related information into one coherent dataset. This capability empowers us to explore more complex relationships in our data, revealing hidden patterns and connections.

Relationship Between Primary and Foreign Keys When Performing JOINS

The relationship between primary and foreign keys is fundamental to the success of JOINS. In a database, a primary key is a unique identifier for each record in a table, ensuring that no two rows have the same key value. Conversely, a foreign key is a column in another table that establishes a link to the primary key of the referenced table.

When performing JOINS, we often utilize primary and foreign keys as the join key to establish relationships between tables. This relationship enforces data integrity and ensures that the data being combined is linked accurately.

For example, consider two tables: “customers” and “orders.” The “customer_id” column in the “orders” table acts as the foreign key, linking to the “customer_id” column in the “customers” table, which serves as the primary key. When we perform a JOIN between these tables using the “customer_id” columns, we can associate orders with their respective customers accurately.

The primary and foreign key relationship forms the backbone of JOINS, creating a harmonious connection between tables and allowing us to conduct more comprehensive data analysis.

INNER JOIN: Finding Common Ground

In the symphony of SQL JOINS, the INNER JOIN takes the spotlight as the conductor of unison, bringing together data that exists in both tables. Like a skilled ensemble, the INNER JOIN orchestrates a harmonious performance, retrieving only the records that share common ground between the participating tables.

INNER JOIN and Its Purpose in Retrieving Data That Exists in Both Tables

The INNER JOIN is a fundamental type of JOIN in SQL, and its purpose is to retrieve data that exists in both tables being joined. When we perform an INNER JOIN, only the rows with matching values in the specified join key from both tables are included in the result set. This allows us to explore the intersection of data, revealing insights where both tables have relevant information to share.

Basic Syntax for Performing INNER JOIN

The syntax for performing an INNER JOIN is as follows:

SELECT columns
FROM table1
INNER JOIN table2
ON table1.join_key = table2.join_key;

Here’s what each part of the syntax represents:

  • columns: These are the specific columns from the tables that you want to include in the result set. You can use “table_name.column_name” notation to avoid ambiguity in case of column name clashes.
  • table1: This is the first table you want to join.
  • table2: This is the second table you want to join.
  • ON: This keyword indicates the join condition, where you specify the join key columns that will be used to match rows between the two tables.

Examples of INNER JOIN to Combine Data from Two Tables with Shared Key Values

Let’s explore some practical examples of INNER JOIN to gain a deeper understanding:

Example 1 — Combining Customer and Order Data:

Consider two tables: “customers” and “orders.” We want to retrieve the names of customers who have placed orders.

SELECT customers.customer_id, customers.customer_name, orders.order_id
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id;

In this example, we use INNER JOIN to combine data from the “customers” and “orders” tables based on the “customer_id” column. The result will include only those customers who have placed orders and their corresponding order IDs.

Example 2 — Uniting Product and Inventory Information:

Suppose we have two tables: “products” and “inventory.” We wish to retrieve the product names and their available quantities in the inventory.

SELECT products.product_id, products.product_name, inventory.quantity_available
FROM products
INNER JOIN inventory
ON products.product_id = inventory.product_id;

In this case, we use INNER JOIN to combine data from the “products” and “inventory” tables based on the “product_id” column. The result will include only products that have inventory records, along with their corresponding available quantities.

LEFT JOIN: Including Everything on the Left

In the symphonic repertoire of SQL JOINS, the LEFT JOIN takes center stage as the conductor of inclusivity, ensuring that no records from the left table are left behind. Like an expansive orchestra, the LEFT JOIN embraces all rows from the left table and selectively welcomes matching records from the right table, creating a harmonious ensemble of data.

LEFT JOIN and Its Role in Retrieving All Records from the Left Table and Matching Records from the Right Table

The LEFT JOIN is a versatile type of JOIN that ensures no data from the left table is omitted in the resulting ensemble. When we perform a LEFT JOIN, all records from the left table are preserved in the result set, regardless of whether they find a matching counterpart in the right table. If a matching record is found in the right table, it is included in the result set alongside the corresponding left table record.

The LEFT JOIN accommodates cases where we want to include data from the primary (left) table, even if there is no direct match in the related (right) table. This is particularly useful for enriching data with additional information while keeping the primary dataset intact.

Basic Syntax for Performing LEFT JOIN

The syntax for performing a LEFT JOIN is as follows:

SELECT columns
FROM table1
LEFT JOIN table2
ON table1.join_key = table2.join_key;

Here’s a breakdown of the syntax:

  • columns: Specify the columns you want to include in the result set, using “table_name.column_name” notation to avoid ambiguity.
  • table1: This is the primary (left) table from which all records will be retained in the result set.
  • table2: This is the related (right) table, from which matching records will be included in the result set.
  • ON: The ON keyword indicates the join condition, where you specify the join key columns that will be used to match rows between the two tables.

Practical Examples of LEFT JOIN to Combine Data While Keeping All Records from the Left Table

Let’s explore practical examples of LEFT JOIN to highlight its inclusive nature:

Example 1 — Combining Customer and Order Data:

Suppose we have two tables: “customers” and “orders.” We want to retrieve customer names along with their order details, including orders that have no associated customer (hypothetically).

SELECT customers.customer_id, customers.customer_name, orders.order_id
FROM customers
LEFT JOIN orders
ON customers.customer_id = orders.customer_id;

In this example, we use LEFT JOIN to combine data from the “customers” and “orders” tables based on the “customer_id” column. The result will include all customers, along with their respective order IDs if they have placed orders. If a customer has not placed any orders, the order_id will be NULL, showcasing the inclusive nature of LEFT JOIN.

Example 2 — Uniting Product and Inventory Information:

Consider two tables: “products” and “inventory.” We wish to retrieve product names along with their available quantities in the inventory, even if they are not present in the “inventory” table.

SELECT products.product_id, products.product_name, inventory.quantity_available
FROM products
LEFT JOIN inventory
ON products.product_id = inventory.product_id;

In this case, we use LEFT JOIN to combine data from the “products” and “inventory” tables based on the “product_id” column. The result will include all products from the “products” table, with their respective available quantities from the “inventory” table if available. If a product has no inventory records, the quantity_available will be NULL, demonstrating the left table’s inclusivity in the result.

RIGHT JOIN: Embracing the Right Side

In the grand orchestration of SQL JOINS, the RIGHT JOIN takes the spotlight as the conductor of inclusion, ensuring that no records from the right table are overlooked. Like a symphony of reciprocity, the RIGHT JOIN embraces all rows from the right table and selectively welcomes matching records from the left table, creating a harmonious ensemble of data.

Introduce the RIGHT JOIN and Its Purpose in Retrieving All Records from the Right Table and Matching Records from the Left Table

The RIGHT JOIN is a counterpart to the LEFT JOIN, and its purpose is to retrieve all records from the right table while preserving matching records from the left table. When we perform a RIGHT JOIN, all rows from the right table are included in the result set, regardless of whether they find a matching counterpart in the left table. If a matching record is found in the left table, it is included in the result set alongside the corresponding right table record.

The RIGHT JOIN accommodates scenarios where we want to retain data from the secondary (right) table, even if there is no direct match in the primary (left) table. This allows us to enrich data with additional information while ensuring that the secondary dataset remains comprehensive.

Basic Syntax for Performing RIGHT JOIN

The syntax for performing a RIGHT JOIN is as follows:

SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.join_key = table2.join_key;

Here’s a breakdown of the syntax:

  • columns: Specify the columns you want to include in the result set, using “table_name.column_name” notation to avoid ambiguity.
  • table1: This is the primary (left) table from which matching records will be retained in the result set.
  • table2: This is the secondary (right) table, from which all records will be included in the result set.
  • ON: The ON keyword indicates the join condition, where you specify the join key columns that will be used to match rows between the two tables.

Practical Examples of RIGHT JOIN to Combine Data While Keeping All Records from the Right Table

Let’s explore practical examples of RIGHT JOIN to highlight its inclusive nature:

Example 1 — Combining Customer and Order Data:

Consider two tables: “customers” and “orders.” We want to retrieve order details along with customer names, ensuring that all orders are included in the result, even if they have no associated customer (hypothetically).

SELECT customers.customer_id, customers.customer_name, orders.order_id
FROM customers
RIGHT JOIN orders
ON customers.customer_id = orders.customer_id;

In this example, we use RIGHT JOIN to combine data from the “customers” and “orders” tables based on the “customer_id” column. The result will include all orders from the “orders” table, along with the corresponding customer names if they exist. If an order has no associated customer, the customer_name will be NULL, demonstrating the right table’s inclusivity in the result.

Example 2 — Uniting Product and Inventory Information:

Suppose we have two tables: “products” and “inventory.” We wish to retrieve available quantities in the inventory along with product names, ensuring that all inventory records are included, even if the products are not present in the “products” table.

SELECT products.product_id, products.product_name, inventory.quantity_available
FROM products
RIGHT JOIN inventory
ON products.product_id = inventory.product_id;

In this case, we use RIGHT JOIN to combine data from the “products” and “inventory” tables based on the “product_id” column. The result will include all inventory records from the “inventory” table, along with the respective product names if they are available in the “products” table. If a product has no corresponding inventory record, the product_name will be NULL, showcasing the right table’s inclusivity in the result.

FULL OUTER JOIN: Embracing All Sides

In the grand symphony of SQL JOINS, the FULL OUTER JOIN takes center stage as the conductor of unity, ensuring that no records from either table are left unheard. Like a harmonious ensemble of inclusivity, the FULL OUTER JOIN brings together all rows from both tables, including unmatched records from each side, creating a comprehensive and resounding symphony of data.

FULL OUTER JOIN and Its Role in Retrieving All Records from Both Tables, Including Unmatched Records from Each Table

The FULL OUTER JOIN is a mighty and versatile type of JOIN that harmonizes the data from both tables in full unison. When we perform a FULL OUTER JOIN, all records from both the primary (left) and secondary (right) tables are included in the result set, regardless of whether they have matching counterparts in the opposite table. If a matching record is found, it is included in the result set alongside the corresponding record from the other table. If no match exists, the result set will contain NULL values for the missing data.

The FULL OUTER JOIN is a powerful tool for examining data relationships comprehensively, uncovering both shared information and unique entities from each table.

Basic Syntax for Performing FULL OUTER JOIN

The syntax for performing a FULL OUTER JOIN is as follows:

SELECT columns
FROM table1
FULL OUTER JOIN table2
ON table1.join_key = table2.join_key;

Here’s an overview of the syntax elements:

  • columns: Specify the columns you want to include in the result set, using “table_name.column_name” notation to avoid ambiguity.
  • table1: This is the primary (left) table, from which all records will be retained in the result set.
  • table2: This is the secondary (right) table, from which all records will be included in the result set.
  • ON: The ON keyword indicates the join condition, where you specify the join key columns that will be used to match rows between the two tables.

Practical Examples of FULL OUTER JOIN to Combine Data and Include All Records from Both Tables

Let’s explore practical examples of FULL OUTER JOIN to highlight its inclusivity:

Example 1 — Combining Customer and Order Data:

Consider two tables: “customers” and “orders.” We want to retrieve customer names along with order details, ensuring that all customers and all orders are included in the result.

SELECT customers.customer_id, customers.customer_name, orders.order_id
FROM customers
FULL OUTER JOIN orders
ON customers.customer_id = orders.customer_id;

In this example, we use FULL OUTER JOIN to combine data from the “customers” and “orders” tables based on the “customer_id” column. The result will include all customers and all orders, along with their respective details if they match. If a customer has no orders or an order has no associated customer, the result will include NULL values in the respective columns, showcasing the comprehensive nature of the FULL OUTER JOIN.

Example 2 — Uniting Product and Inventory Information:

Suppose we have two tables: “products” and “inventory.” We wish to retrieve product names along with available quantities in the inventory, ensuring that all products and all inventory records are included in the result.

SELECT products.product_id, products.product_name, inventory.quantity_available
FROM products
FULL OUTER JOIN inventory
ON products.product_id = inventory.product_id;

In this case, we use FULL OUTER JOIN to combine data from the “products” and “inventory” tables based on the “product_id” column. The result will include all products and all inventory records, along with their respective available quantities if they match. If a product has no corresponding inventory record or an inventory record has no associated product, the result will include NULL values in the respective columns, demonstrating the inclusive nature of the FULL OUTER JOIN.

Comparing JOIN Types and Use Cases

As our SQL symphony reaches its crescendo, it’s essential to understand the unique harmonies produced by each type of JOIN. Let’s compare the INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN, examining their distinct melodies and exploring when to use each one based on specific data analysis requirements.

Differences Between INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN

  1. INNER JOIN: The INNER JOIN retrieves only the matching records from both tables, excluding unmatched rows. It focuses on finding common ground between the tables and presents data where the join key values align in both datasets.
  2. LEFT JOIN: The LEFT JOIN preserves all records from the primary (left) table and includes matching records from the secondary (right) table. If there’s no match in the right table, NULL values are displayed for the right table columns. The LEFT JOIN is ideal when you want to retain all primary table data while enriching it with related information from the secondary table.
  3. RIGHT JOIN: The RIGHT JOIN mirrors the LEFT JOIN, preserving all records from the secondary (right) table and including matching records from the primary (left) table. If there’s no match in the left table, NULL values are displayed for the left table columns. The RIGHT JOIN is useful when you want to retain all secondary table data while adding relevant information from the primary table.
  4. FULL OUTER JOIN: The FULL OUTER JOIN combines all records from both tables, including unmatched rows from both sides. When there’s no match in either table, NULL values are displayed for the respective columns. The FULL OUTER JOIN is valuable when you need to analyze and compare all data from both tables comprehensively, regardless of matches.

Conclusion

As we draw the final curtain on our SQL JOIN symphony, we leave behind a harmonious trail of data exploration and discovery. From the virtuosic performances of INNER JOIN, LEFT JOIN, RIGHT JOIN, to the grand unison of the FULL OUTER JOIN, we have explored the intricacies of combining data from multiple tables, weaving melodies of insights that resonate with brilliance.

Through the magic of INNER JOIN, we found common ground, unearthing shared information and relationships between datasets. With the inclusivity of LEFT JOIN, we preserved the integrity of the primary dataset while enriching it with supplementary details. The reciprocal embrace of RIGHT JOIN allowed us to focus on the secondary dataset, enhanced with primary table data. In the symphony of FULL OUTER JOIN, we attained a panoramic view of both datasets, encompassing matches and mismatches alike.

Each JOIN type played a pivotal role, adding its distinct voice to our data symphony. By comparing and contrasting their melodies, we learned when to employ each JOIN type based on specific data analysis requirements, crafting insightful compositions that echoed with precision and depth.

As we part ways, let us carry forth our newfound expertise, conducting further explorations in the realms of SQL. Continue to orchestrate data symphonies, unravel relationships, and extract valuable insights, turning data into a harmonious symphony of knowledge.

📝🎵 The journey of SQL mastery continues, and the world of data awaits your artistic touch! 🎻🎹

--

--

Brandon Wohlwend

Mathematician | Data Science, Machine Learning | Java, Software Engineering