What is INNER JOIN?
An INNER JOIN is a type of SQL join that returns only the rows that have matching values in both tables. It is used to combine data from two or more tables based on a related column.
Syntax of INNER JOIN
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
- table1, table2 – Names of the tables you want to join.
- column – The common column used to match records in both tables.
- columns – The list of columns you want to display in the result.
How INNER JOIN Works
- SQL looks for matching values in the specified columns of both tables.
- Only rows that satisfy the matching condition are returned.
- Rows with no match in either table are excluded.
Example 1: Basic INNER JOIN
Suppose we have two tables:
Customers
CustomerID, Name
Orders
OrderID, CustomerID, OrderDate
We want a list of customers with their orders:
SELECT Customers.Name, Orders.OrderID, Orders.OrderDate
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID;
Result:
Only customers who have placed an order will appear in the result. Customers without orders are excluded.
Example 2: INNER JOIN with Multiple Columns
You can join on more than one column if necessary:
SELECT A.Name, B.OrderID
FROM Customers A
INNER JOIN Orders B
ON A.CustomerID = B.CustomerID AND A.Region = B.Region;
This will return rows where both CustomerID and Region match in both tables.
Key Points to Remember
- INNER JOIN only returns matching rows.
- If no match exists, the row is not included.
- Multiple INNER JOINs can be used to join more than two tables.
- Aliases (like A and B) can simplify queries with long table names.