7 Joining Tables with INNER JOIN

Joining Tables with INNER JOIN

In SQL, the INNER JOIN is used to combine rows from two or more tables based on a related column between them. It is one of the most common types of joins used in database queries. Let's take a look at some example queries to better understand how INNER JOIN works.

Example 1: Combining Data from Two Tables

Suppose we have two tables: customers and orders. The customers table contains information about customers, including their customer_id and customer_name. The orders table contains information about orders, including the order_id, customer_id, and order_date.

We can use INNER JOIN to combine data from both tables based on the customer_id column:


SELECT *
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id;     

This query will return all the columns from both tables where the customer_id values match.

Example 2: Joining Multiple Tables

Sometimes we need to combine data from more than two tables. In this example, we have three tables: customers, orders, and order_details. The order_details table contains information about the products in each order, including the order_id, product_id, and quantity.

We can use INNER JOIN to combine data from all three tables based on the customer_id and order_id columns:


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

This query will return the customer name, order date, product ID, and quantity for all orders in the database.

Conclusion

INNER JOIN is a powerful tool in SQL for combining data from multiple tables. By understanding how to use INNER JOIN, you can easily retrieve the information you need from a complex database.

Comments