13.1 Joins in MySQL
13.1 Joins in MySQL
In MySQL, a join is a database operation that combines rows from two or more tables based on a related
column between them.
The primary purpose of a join is to retrieve and display data from multiple tables in a single result set,
allowing you to access and analyze data that is distributed across different tables within a database.
1. Combining Data:
Joins allow you to combine data from multiple tables into a single result set.
This is particularly useful when data is spread across different tables, and you need to
consolidate it for analysis or reporting.
2. Related Columns:
To perform a join, you specify one or more columns from each table that have a relationship.
This relationship is typically established through primary keys and foreign keys, where a column
in one table matches a column in another table.
3. Types of Joins:
MySQL supports various types of joins, including INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL
JOIN.
Each type of join combines rows differently and includes or excludes rows based on the match
condition.
4. Syntax:
The basic syntax of a join involves specifying the tables to be joined and the join condition using
the ON clause.
You can also use additional clauses like WHERE to further filter the result set.
5. Result Set:
The result of a join is a new virtual table that combines columns from both tables based on the
specified condition.
This virtual table can be used like any other table in SQL queries.
Types of Joins
In MySQL, there are several types of joins that allow you to combine data from multiple tables based on
a related column between them.
3. SELF JOIN
Inner Join
An INNER JOIN in MySQL is a type of SQL join operation that combines rows from two or more tables
based on a related column between them.
The result of an INNER JOIN includes only the rows that have matching values in both tables being
joined.
If there's no match between the tables based on the specified join condition, those rows are excluded
from the result set.
Combining Data:
An INNER JOIN is used to retrieve data from multiple tables by matching rows based on a
specified condition.
It combines rows from two or more tables into a single result set.
Related Columns:
To perform an INNER JOIN, you specify one or more columns from each table that have a
relationship.
This relationship is typically established through primary keys and foreign keys, where a column
in one table matches a column in another table.
Matching Rows:
When you perform an INNER JOIN, MySQL looks for rows where the values in the specified
columns match between the tables.
Rows that meet this condition are included in the result set, while rows that don't have
matching values are excluded.
Here's the basic syntax of an INNER JOIN
SELECT
columns
FROM table1
In this syntax:
SELECT columns:
Specifies the columns you want to retrieve from the combined result of the join.
You can select columns from either or both of the tables being joined.
table1 represents the first table, and table2 represents the second table.
ON table1.column_name = table2.column_name:
Defines the join condition by specifying which columns should be compared for equality
between the two tables.
Rows where these columns have matching values are included in the result set.
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100),
phone_number VARCHAR(15)
);
-- Create the Orders table
customer_id INT,
order_date DATE,
);
VALUES
-- Customer 1
VALUES
-- Customer 2
VALUES
-- Customer 3
VALUES
-- Customer 4
VALUES
-- Customer 5
VALUES
VALUES
-- Customer 7
VALUES
-- Customer 8
VALUES
-- Customer 9
INSERT INTO Orders (customer_id, order_date, total_amount)
VALUES
-- Customer 10
VALUES
-- Customer 11
VALUES
-- Customer 12
VALUES
(12, '2023-06-05', 200.00),
-- Customer 13
VALUES
-- Customer 14
VALUES
-- Customer 15
VALUES
-- Customer 16
VALUES
-- Customer 17
VALUES
-- Customer 18
VALUES
-- Customer 19
VALUES
-- Customer 20
VALUES
-- Customer 21
VALUES
VALUES
-- Customer 23
VALUES
-- Customer 24
VALUES
-- Customer 25
-- Customer 26
VALUES
-- Customer 27
VALUES
-- Customer 28
VALUES
-- Customer 29
VALUES
This query retrieves customer information along with their order details.
SELECT
Customers.first_name,
Customers.last_name,
Orders.order_date,
Orders.total_amount
FROM Customers
Customers.first_name,
Customers.last_name,
Orders.order_date,
Orders.total_amount
FROM Customers
WHERE Customers.customer_id = 1;
This query calculates the total order amount for each customer.
SELECT
Customers.customer_id,
Customers.first_name,
Customers.last_name,
SUM(Orders.total_amount) AS total_order_amount
FROM Customers
GROUP BY
Customers.customer_id,
Customers.first_name,
Customers.last_name;
SELECT
Customers.first_name,
Customers.last_name,
Orders.order_date,
Orders.total_amount
FROM Customers
VALUES
SELECT
DISTINCT Customers.first_name,
Customers.last_name
FROM Customers
Customers.first_name,
Customers.last_name
FROM Customers
The following query retrieve orders and customer information sorted by order date:
SELECT
Customers.first_name,
Customers.last_name,
Orders.order_date,
Orders.total_amount
FROM Customers
ORDER BY Orders.order_date;
SELECT
Customers.first_name,
Customers.last_name,
MAX(Orders.order_date) AS last_order_date
FROM Customers
Find customers and the total number of orders they have placed:
SELECT
Customers.first_name,
Customers.last_name,
COUNT(Orders.order_id) AS total_orders
FROM Customers
To find customers who have placed orders with a total amount greater than a specific threshold (e.g.,
$500):
SELECT
Customers.first_name,
Customers.last_name,
SUM(Orders.total_amount) AS total_order_amount
FROM Customers
Outer Join
An outer join is a type of SQL join that retrieves records from two tables, even if there is no match
between the columns being joined.
It includes unmatched rows from one or both tables in the result set, depending on the type of outer
join used.
There are three main types of outer joins:
1. LEFT OUTER JOIN (or LEFT JOIN): This type of join returns all the rows from the left table and the
matching rows from the right table. If there are no matching rows in the right table, it returns
NULL values for the right table's columns.
2. RIGHT OUTER JOIN (or RIGHT JOIN): This type of join returns all the rows from the right table
and the matching rows from the left table. If there are no matching rows in the left table, it
returns NULL values for the left table's columns.
3. FULL OUTER JOIN (or FULL JOIN): This type of join returns all the rows when there is a match in
either the left or right table. It includes all rows from both tables and returns NULL values for
columns where there is no match.
Outer joins are useful when you want to retrieve data from one table and include any related
data from another table but don't want to exclude rows from either table if there's no match.
They are particularly helpful for working with tables that have optional relationships or missing
data in some cases.
This query retrieves customer information along with the details of their orders. Customers who have
not placed any orders will also be included in the result with NULL values for order-related columns.
SELECT
Customers.first_name,
Customers.last_name,
Orders.order_id,
Orders.order_date,
Orders.total_amount
FROM Customers
This query counts the number of orders for each customer. It also includes customers who have not
placed any orders, showing a count of 0 for them.
SELECT
Customers.first_name,
Customers.last_name,
COUNT(Orders.order_id) AS order_count
FROM Customers
3. Retrieve Customers Who Placed Orders in January 2023 (including customers with no January
orders):
This query retrieves customers who placed orders in January 2023 along with their order details.
Customers who did not place orders in January will still be included in the result.
SELECT
Customers.first_name,
Customers.last_name,
Orders.order_id,
Orders.order_date,
Orders.total_amount
FROM Customers
This query retrieves customer information along with the details of their orders. It also includes orders
that do not have associated customers, showing NULL values for customer-related columns.
SELECT
Customers.first_name,
Customers.last_name,
Orders.order_id,
Orders.order_date,
Orders.total_amount
FROM Customers
2. Count the Number of Orders for Each Customer (including customers with no orders):
This query counts the number of orders for each customer. It also includes customers who have not
placed any orders, showing a count of 0 for them.
SELECT
Customers.first_name,
Customers.last_name,
COUNT(Orders.order_id) AS order_count
FROM Orders
This query retrieves orders placed by customers whose email addresses have specific domains (e.g.,
"@appteknow.com"). It includes orders that do not have associated customers with matching email
domains.
UPDATE Customers
LIMIT 15;
UPDATE Customers
WHERE customer_id IN (
SELECT customer_id
FROM (
SELECT customer_id
FROM Customers
LIMIT 5
) AS subquery
);;
SELECT
Customers.first_name,
Customers.last_name,
Customers.email,
Orders.order_id,
Orders.order_date,
Orders.total_amount
FROM Orders
In MySQL, a FULL JOIN is not directly supported. Instead, you can achieve a similar result by combining a
LEFT JOIN and a RIGHT JOIN with a UNION statement. Here's how you can modify the queries to achieve
a similar result:
1. Retrieve All Customers and Their Orders (including unmatched rows from both tables):
SELECT
Customers.first_name,
Customers.last_name,
Orders.order_id,
Orders.order_date,
Orders.total_amount
FROM Customers
UNION
SELECT
Customers.first_name,
Customers.last_name,
Orders.order_id,
Orders.order_date,
Orders.total_amount
FROM Customers
2. Count the Number of Orders for Each Customer (including customers with no orders and orders
with no customers):
SELECT
Customers.first_name,
Customers.last_name,
COUNT(Orders.order_id) AS order_count
FROM Customers
UNION
SELECT
Customers.first_name,
Customers.last_name,
COUNT(Orders.order_id) AS order_count
FROM Customers
SELECT
p.ProductName,
p.UnitPrice,
c.CategoryName
FROM products p
This query retrieves a list of product names, their unit prices, and their
corresponding category names by joining the products and categories tables on
the CategoryID column.
2. Get Customer Orders with Product Details:
SELECT
o.OrderID,
c.ContactName,
od.Quantity,
p.ProductName
FROM orders o
This query retrieves a list of customer orders along with the product details for each
order. It joins the orders, customers, order_details, and products tables to
achieve this.
This query retrieves a list of customers along with the total order amount for
each customer. It joins the customers, orders, and order_details tables.
SELECT
c.CustomerID,
c.ContactName,
FROM customers c
GROUP BY c.CustomerID;
SELECT
e.EmployeeID,
e.FirstName,
e.LastName,
GROUP_CONCAT(t.TerritoryDescription) AS Territories
FROM employees e
GROUP BY e.EmployeeID;
p.ProductName,
s.CompanyName AS Supplier,
c.CategoryName
FROM products p
-- This query identifies customers who have not placed any orders. It
uses a LEFT JOIN to combine the customers and orders tables.
SELECT
c.CustomerID,
c.ContactName
FROM customers c
SELECT
MONTH(o.OrderDate) AS Month,
p.ProductName,
FROM orders o
SELECT
p.ProductName,
s.CompanyName AS Supplier,
c.CategoryName,
e.FirstName AS Employee,
cu.ContactName AS Customer
FROM products p
SELECT
e.EmployeeID,
e.FirstName,
e.LastName,
GROUP_CONCAT(t.TerritoryDescription) AS Territories,
o.OrderID,
o.OrderDate,
COUNT(od.ProductID) AS ShippedProducts
FROM employees e
-- This query retrieves a list of customers along with the orders they
placed, the products ordered, and the suppliers of those products.
SELECT
cu.CustomerID,
cu.ContactName AS Customer,
o.OrderID,
p.ProductName,
s.CompanyName AS Supplier
FROM customers cu
SELECT
p.ProductName,
c.CategoryName,
o.OrderID,
e.FirstName AS Employee,
s.CompanyName as Shipper
FROM products p