SQL INNER JOIN Keyword
The INNER JOIN
keyword is used in SQL to combine rows from two or more tables based on a related column between them. It only returns rows where there's a match in both tables.
INNER JOIN: Definition and Usage
Imagine you have two tables: one with customer details and another with their orders. INNER JOIN
lets you efficiently combine these tables to show customer information alongside their corresponding orders. If an order doesn't have a matching customer, or vice-versa, that row is excluded from the result.
Syntax
The basic syntax looks like this:
Syntax
SELECT column_names
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;
Examples
Joining Two Tables
This example combines the 'Orders' and 'Customers' tables to retrieve order IDs and customer names.
Syntax
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Output
A table is returned showing each order's ID and the name of the customer who placed it. Orders without a matching customer ID in the `Customers` table are not included.
OrderID | CustomerName
-----------------------
1 | John Doe
2 | Jane Smith
Joining Multiple Tables
INNER JOIN
can be used multiple times to combine data from more than two tables. This example adds shipper information to the previous query.
Syntax
SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID;
Output
A table is returned including the OrderID, CustomerName, and ShipperName. Only orders with matching CustomerID and ShipperID in their respective tables are shown.
OrderID | CustomerName | ShipperName
------------------------------------
1 | John Doe | Speedy Express
2 | Jane Smith | Fast Delivery