CodeNewbie Community 🌱

Cover image for MySQL JOINs
maksimmos16
maksimmos16

Posted on

MySQL JOINs

Imagine you're tasked with building a dynamic e-commerce platform. Your database houses information about products, customers, orders, and more. Each of these entities resides in its own table, neatly organized to ensure data integrity and scalability. However, to provide users with a comprehensive shopping experience, you often need to pull data from multiple tables simultaneously.

This is precisely where MySQL joins become indispensable. Joins allow you to merge data from different tables based on common fields, enabling you to construct complex queries that fetch precisely the information you need. Whether you're displaying a product catalog with associated customer reviews, generating sales reports spanning multiple years, or personalizing recommendations based on user behavior, joins empower you to wield the full potential of your database.

1. Understanding the Basics of Joins:
In the realm of database management, a "join" refers to the operation of combining rows from two or more tables based on a related column between them. By joining tables, you can create a unified dataset that incorporates information from multiple sources, facilitating more comprehensive queries and data analysis.

Types of Joins:

In MySQL, there are several types of joins, each serving a specific purpose:

INNER JOIN: An INNER JOIN returns rows from both tables where there is a match based on the specified condition. It filters out rows that don't have corresponding entries in both tables.

LEFT JOIN: A LEFT JOIN returns all rows from the left table (the first table specified in the query) and the matched rows from the right table. If there are no matches in the right table, NULL values are returned for the columns from that table.

RIGHT JOIN: Similar to a LEFT JOIN, a RIGHT JOIN returns all rows from the right table (the second table specified in the query) and the matched rows from the left table. If there are no matches in the left table, NULL values are returned for the columns from that table.

OUTER JOIN (or FULL OUTER JOIN): An OUTER JOIN returns all rows from both tables, pairing rows where there is a match based on the specified condition and filling in NULL values for unmatched rows in either table.

Image description

2. INNER JOIN:

In MySQL, an INNER JOIN is used to retrieve records from two or more tables where there is a match between the columns in those tables based on a specified condition. The result of an INNER JOIN is a new table containing only the rows that have matching values in both tables. If there are no matching values, the row is not included in the result set.

Syntax:

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

Enter fullscreen mode Exit fullscreen mode

SELECT: Specifies the columns you want to retrieve from the tables.
FROM: Specifies the first table.
INNER JOIN: Specifies that you're performing an inner join.
ON: Specifies the condition for the join, indicating which columns to match.
Use Cases:

INNER JOINs are most appropriate when you want to retrieve only the rows that have matching values in both tables involved in the join. Common use cases include:

Relational Data Retrieval: Fetching related information from multiple tables, such as retrieving order details along with customer information.
Data Filtering: Narrowing down the result set based on specific criteria present in both tables.
Entity Relationship Queries: Connecting entities in a database schema to retrieve cohesive information.

Example 1: Retrieving Order Details with Customer Information:
Suppose you have two tables: orders and customers. You want to retrieve details of orders along with the corresponding customer information.

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

Enter fullscreen mode Exit fullscreen mode

This query retrieves the order_id, order_date, and customer_name from the orders and customers tables, respectively, joining them on the customer_id column.

Example 2: Fetching Blog Posts with Associated Categories:
Consider two tables: posts and categories. You wish to fetch blog posts along with their associated categories.

SELECT posts.title, categories.category_name
FROM posts
INNER JOIN categories ON posts.category_id = categories.category_id;

Enter fullscreen mode Exit fullscreen mode

This query retrieves the title of each blog post along with its corresponding category_name, joining the posts and categories tables on the category_id column.

3. LEFT JOIN and RIGHT JOIN:

In MySQL, both LEFT JOIN and RIGHT JOIN are types of outer joins that allow you to retrieve all records from one table (the left or right table) and only the matching records from the other table (the right or left table). If there are no matching records in the other table, NULL values are included in the result set.

LEFT JOIN: Returns all records from the left table and matching records from the right table. If there are no matching records in the right table, NULL values are used.

RIGHT JOIN: Returns all records from the right table and matching records from the left table. If there are no matching records in the left table, NULL values are used.

When to Use Each:
LEFT JOIN: Use when you want to retrieve all records from the left table regardless of whether there are matching records in the right table. This is commonly used when you have a primary table (e.g., customers) and want to retrieve related information from another table (e.g., orders), ensuring that all customers are included even if they haven't placed any orders.

RIGHT JOIN: Use when you want to retrieve all records from the right table regardless of whether there are matching records in the left table. While less common than LEFT JOIN, it can be useful in situations where the primary focus is on the table on the right side of the join.

Example 1: LEFT JOIN - Retrieving Customers with Their Orders:

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

Enter fullscreen mode Exit fullscreen mode

This query retrieves all customers along with their orders (if any). Even if a customer hasn't placed any orders, their information will still be included in the result set with NULL values for order-related columns.

Example 2: RIGHT JOIN - Fetching Employees with Their Assigned Departments:

SELECT employees.employee_id, employees.employee_name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.department_id;

Enter fullscreen mode Exit fullscreen mode

This query retrieves all departments along with the employees assigned to them (if any). Departments without any assigned employees will still be included in the result set with NULL values for employee-related columns.

Comparison:
LEFT JOIN vs. RIGHT JOIN: The primary distinction between LEFT JOIN and RIGHT JOIN lies in which table's records are preserved in the result set. In LEFT JOIN, all records from the left table are included, while in RIGHT JOIN, all records from the right table are preserved.

Practical Example: Imagine you're building an HR management system. If you want to ensure that all departments are included in your report, regardless of whether they have employees assigned, you'd use RIGHT JOIN to prioritize the department table. Conversely, if you want to ensure that all employees are listed, even if they're not yet assigned to a department, you'd opt for LEFT JOIN to prioritize the employee table.

4. OUTER JOIN:

In MySQL, an OUTER JOIN is used to retrieve all records from one or both tables involved in the join, regardless of whether there is a matching row in the other table. Unlike INNER JOIN, which only includes matching rows, OUTER JOIN ensures that unmatched rows are also included in the result set. There are three types of OUTER JOIN: LEFT OUTER JOIN, RIGHT OUTER JOIN, and FULL OUTER JOIN.

Variants of OUTER JOIN:
LEFT OUTER JOIN (or LEFT JOIN): Retrieves all records from the left table and the matched records from the right table. If there are no matching records in the right table, NULL values are returned for the columns from the right table.

RIGHT OUTER JOIN (or RIGHT JOIN): Retrieves all records from the right table and the matched records from the left table. If there are no matching records in the left table, NULL values are returned for the columns from the left table.

FULL OUTER JOIN: Retrieves all records from both tables, including unmatched rows from both tables. If there is no matching record in the other table, NULL values are returned for the columns from the respective table.

Use Cases:

OUTER JOINs are necessary when you want to include unmatched rows from one or both tables in the result set. This is particularly useful in scenarios where:

You need to include all records from one table, regardless of whether there are matches in the other table.
You want to perform a comparison between two datasets and retain all records from both sides.
You're conducting data analysis where missing values need to be accounted for.

Example 1: Retrieving Employees and Their Assigned Departments:
Consider two tables: employees and departments. You want to retrieve all employees along with their assigned departments. Some employees may not be assigned to any department yet.

SELECT employees.employee_id, employees.employee_name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.department_id;

Enter fullscreen mode Exit fullscreen mode

This query uses a LEFT JOIN to retrieve all employees, including those who are not yet assigned to any department. If an employee is not assigned to a department, the department_name column will contain NULL.

Example 2: Combining User Profiles and Subscription Information:
Suppose you have two tables: users and subscriptions. You want to combine user profiles with subscription information, ensuring that all users are included in the result, even if they don't have an active subscription.

SELECT users.user_id, users.username, subscriptions.plan_name
FROM users
RIGHT JOIN subscriptions ON users.user_id = subscriptions.user_id;

Enter fullscreen mode Exit fullscreen mode

In this query, a RIGHT JOIN is used to retrieve all subscriptions, including those users who do not have an active subscription. If a user does not have a subscription, the plan_name column will contain NULL.

More info:

https://www.cloudways.com/blog/how-to-join-two-tables-mysql/
https://spacema-dev.com/mysql-joins-tutorial-for-beginners-with-examples/https://dev.mysql.com/doc/refman/8.0/en/join.html

Top comments (0)