SQL Inner Join
An INNER JOIN in SQL selects records that have matching values in both tables. If a row in one table does not have a corresponding match in the other, it is completely excluded from the result set.
By default, simply writing JOIN in your query performs an INNER JOIN.
Syntax
To implement an inner join, name your primary table, use the INNER JOIN keyword to declare the secondary table, and use the ON keyword to specify the connecting columns (usually a Primary Key matching a Foreign Key).
SELECT columns
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;
- INNER JOIN: Identifies the second table you want to combine with your first.
- ON: Specifies the matching condition (typically linking a primary key from one table to a foreign key in another).
Note: The word INNER is optional in almost all modern databases. Writing JOIN by itself defaults to an inner join.
Visual Concept & Practical Example
Think of an INNER JOIN like a Venn diagram intersection: only the overlapping data between the two sets is returned.
Sample Tables:
Customers Table
| customer_id | name |
|---|---|
| 1 | Alice |
| 2 | Bob |
| 3 | Charlie |
Orders Table
| order_id | customer_id | product |
|---|---|---|
| 101 | 1 | Laptop |
| 102 | 2 | Phone |
| 103 | 5 | Tablet |
The Query:
SELECT Customers.name, Orders.product
FROM Customers
INNER JOIN Orders
ON Customers.customer_id = Orders.customer_id;
Result:
| name | product |
|---|---|
| Alice | Laptop |
| Bob | Phone |
- Why Charlie is missing: Charlie (customer_id 3) hasn't placed any orders, so there is no match in the Orders table.
- Why Order 103 is missing: Order 103 belongs to customer_id 5, which doesn't exist in the Customers table.
Pro-Tip: Table Aliases
To avoid typing out long table names repeatedly and fix ambiguity errors, use short text aliases:
SELECT c.name, o.product
FROM Customers c
INNER JOIN Orders o
ON c.customer_id = o.customer_id;
Combining INNER JOIN with a WHERE Filter
You can seamlessly add standard filtering rules to your joined datasets. The WHERE clause must always be placed after the join declarations.
-- Finds only the employees working in the Engineering department
SELECT e.name, d.department_name
FROM employees AS e
INNER JOIN departments AS d ON e.department_id = d.department_id
WHERE d.department_name = 'Engineering';
Joining Multiple Tables Seamlessly
If you need to string three or more tables together, you can simply chain subsequent INNER JOIN statements sequentially.
-- Connects a customer to their order, and that order to the specific product item
SELECT c.customer_name, o.order_date, p.product_name
FROM customers AS c
INNER JOIN orders AS o ON c.customer_id = o.customer_id
INNER JOIN order_items AS oi ON o.order_id = oi.order_id
INNER JOIN products AS p ON oi.product_id = p.product_id;