Retrieve Records from Multiple Tables in MySQL
Last Updated :
21 Jun, 2024
In relational databases like MySQL, data is often spread across multiple tables to maintain normalization and avoid redundancy. To effectively work with such data, you need to combine and retrieve records from these tables using various types of joins and other methods. This article will guide you through different ways to retrieve records from multiple tables in MySQL.
How to Retrieve Records from Multiple Tables in MySQL
The JOIN keyword connects two or more tables based on a specific column. This can be used to access records of both tables and retrieve them in a single SELECT statement.
The syntax for utilizing JOINs in MySQL hinges on the JOIN keyword followed by the table names and the JOIN type, along with the ON clause to define the joining condition.
Syntax:
SELECT column1, column2, ...
FROM table1
JOIN table2 ON table1.column_name = table2.column_name;
Parameters:
- SELECT: Specifies the columns you wish to retrieve from the joined tables.
- FROM: Indicates the tables involved in the JOIN.
- JOIN: Initiates the JOIN operation.
- table1, table2: Names of the tables being joined.
- ON: Defines the condition that establishes the relationship between the tables.
Retrieve Records From Multiple Tables Examples
Let's look at some examples of how to retrieve records from multiple tables in MySQL.
First, let's create a demo MySQL database on which we will perform the MySQL queries.
CREATE TABLE customers (
id INT PRIMARY KEY,
name VARCHAR(50)
);
INSERT INTO customers (id, name) VALUES
(1, 'John Doe'),
(2, 'Jane Smith'),
(3, 'David Lee');
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
product_name VARCHAR(50),
FOREIGN KEY (customer_id) REFERENCES customers(id)
);
INSERT INTO orders (order_id, customer_id, product_name) VALUES
(1234, 1, 'Laptop'),
(5678, 2, 'Smartphone');
SELECT * FROM orders;
SELECT * FROM customers;
Output:
customers table:
id | name |
---|
1 | John Doe |
2 | Jane Smith |
3 | David Lee |
orders table:
order_id | customer_id | product_name |
---|
1234 | 1 | Laptop |
5678 | 2 | Smartphone |
After creating the demo tables, let's look at MySQL queries to retrieve records from multiple tables.
Using INNER JOIN to Retrieve Records From Multiple Tables
In this example, we have created a database as Record and Consider two tables customers and orders. We want to retrieve customer names and their corresponding order details with the help of foreign keys as written here.
SELECT customers.name, orders.order_id, orders.product_name
FROM customers
INNER JOIN orders ON customers.id = orders.customer_id;
Output:
This query will only return records where a customer in the customers table has a matching entry in the orders table, based on the customer_id column.
+------------+----------+--------------+
| name | order_id | product_name |
+------------+----------+--------------+
| John Doe | 1234 | Laptop |
| Jane Smith | 5678 | Smartphone |
+------------+----------+--------------+
Explanation: The SELECT query retrieves the names of customers along with order details such as order_id and product_name by performing an INNER JOIN on the 'customers' and 'orders' tables using the common key 'id' and 'customer_id', respectively.
Using LEFT JOIN to Retrieve Records From Multiple Tables
Retrieve customer names and their corresponding order details with the help of a foreign key.
SELECT customers.name, orders.order_id, orders.product_name
FROM customers
LEFT JOIN orders ON customers.id = orders.customer_id;
Output:
This query will include all customers from the customers table, with matching order details from the orders table if available. If no order exists for a customer, the order_id and product_name columns will be populated with NULL values.
+------------+----------+--------------+
| name | order_id | product_name |
+------------+----------+--------------+
| John Doe | 1234 | Laptop |
| Jane Smith | 5678 | Smartphone |
| David Lee | NULL | NULL |
+------------+----------+--------------+
Explanation: The SELECT query fetches customer names along with order details such as order_id and product_name. It uses a LEFT JOIN to include all customers, even those without orders, linking them based on the common key 'id' and 'customer_id'.
Using UNION
-- Retrieve customer names from the customers table
SELECT name AS item_name
FROM customers
UNION
-- Retrieve product names from the orders table
SELECT product_name AS item_name
FROM orders;
Output:
+------------+
| item_name |
+------------+
| John Doe |
| Jane Smith |
| David Lee |
| Laptop |
| Smartphone |
+------------+
Explanation: This UNION operation combines the results of two queries into a single result set. It retrieves customer names from the 'customers' table and product names from the 'orders' table, ensuring there are no duplicate rows.
Conclusion
Retrieving records from multiple tables in MySQL is a common requirement and can be accomplished using various types of joins, subqueries, and UNION operations. Understanding these techniques allows you to efficiently query your database and extract the necessary data for your applications. Use INNER JOIN for matching records, LEFT JOIN or RIGHT JOIN when you need all records from one table regardless of matches, and UNION or subqueries for more complex retrieval scenarios.
Similar Reads
How to Retrieve Data From Multiple Tables in PL/SQL?
Retrieving data from multiple tables is a common task in PL/SQL and It is a skill that can significantly enhance our data manipulation capabilities. Whether we are joining tables to fetch related data or using subqueries to extract specific information, knowing how to navigate multiple tables is ess
4 min read
How to Retrieve Data from Multiple Tables in PL/SQL
PL/SQL is âProcedural Language extensions to the Structured Query Languageâ. SQL is a popular language for both querying and updating data in relational database management systems (RDBMS). PL/SQL adds many procedural constructs to SQL language to overcome some limitations of SQL. In addition, PL/SQ
5 min read
How to Retrieve Data from Multiple Tables in SQL?
In SQL, retrieving data from multiple tables is a common requirement in database operations. Efficiently combining data from different tables allows developers to create complex queries and extract valuable insights from interconnected datasets. In this article, we will explore multiple approaches t
5 min read
SELECT data from Multiple Tables in SQL
In SQL (Structured Query Language), it is a common requirement to retrieve data from more than one table at once. When you work with relational databases, you often have to combine data from multiple tables to get meaningful results. SQL provides many methods for selecting data from multiple tables,
4 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we con
3 min read
Querying Multiple Tables in SQL
SQL (Structured Query Language) is a powerful tool for managing and querying relational databases. One of its most valuable features is the ability to query multiple tables simultaneously, allowing us to retrieve and integrate related data efficiently. In this article, we will explain how to query m
4 min read
SQLAlchemy Core - Multiple Tables
SQLAlchemy is an open-source library that provides a set of tools for working with relational databases. It offers a high-level Object-Relational Mapping (ORM) interface as well as a lower-level SQL Expression Language (Core) interface. SQLAlchemy Core is a lightweight and flexible SQL toolkit that
4 min read
How to Retrieve Data From Multiple Tables Using PL/SQL Cursors
In database programming, the ability to retrieve data from multiple tables is essential for building robust and efficient applications. PL/SQL Cursors is a powerful feature that enables developers to navigate through result sets and make them the best option for querying data from multiple tables. I
4 min read
How To Update Multiple Columns in MySQL?
To update multiple columns in MySQL we can use the SET clause in the UPDATE statement. SET clause allows users to update values of multiple columns at a time. In this article, we will learn how to update multiple columns in MySQL using UPDATE and SET commands. We will cover the syntax and examples,
3 min read
SQL Query to Get the Latest Record from the Table
Fetching the latest record from a table is a frequent and essential task when managing relational databases. Whether you want to retrieve all columns or a specific subset of them, SQL provides a variety of techniques to accomplish this efficiently. In this article, we will explain how to retrieve th
5 min read