In this lesson, you will learn how to stitch data together from two separate tables using INNER JOIN to create a unified view of related information.
Bringing Tables Together
So far, we have worked with data stored in single tables. However, in a normalized database, we often split related information into different tables to avoid redundancy. For example, you might have a Customers table and an Orders table. To see which customer placed which order, we need to bridge the gap between these tables using a shared key.
An INNER JOIN acts like a filter that matches records from both tables based on a common value—usually the Primary Key of one table and a corresponding Foreign Key in the other.
The Syntax
To perform an INNER JOIN, you specify the two tables you want to combine and the condition they share using the ON keyword.
SELECT Customers.Name, Orders.OrderDate
FROM Customers
INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
How it Works
When the database engine processes this query, it looks at the CustomerID in the Customers table and finds every row in the Orders table that shares that exact same ID.
- The Match: If a customer has an ID of
5and there is an order with aCustomerIDof5, the database combines those two rows into a single result row. - The Exclusion: If a customer has never placed an order (or an order exists with a customer ID that isn't in your
Customerstable), those records are excluded from the results entirely.
An INNER JOIN only returns rows where there is a match on both sides. If a record doesn't have a partner in the other table, it simply doesn't appear in your output. This allows you to effectively query the relationship between entities as if they were stored in one large, logical table, while maintaining the clean structure of your physical design.
Key Takeaway: An INNER JOIN combines records from two tables only when the specified join condition is met, effectively filtering out any rows that do not have a corresponding match in the other table.