SQL INNER JOIN
SQL INNER JOIN is a type of join operation used to combine data from two or more tables based on the values of the columns they have in common. INNER JOIN returns only the rows from both tables where the join condition is met, discarding all the rest of the rows.
Let's consider two tables, 'Customers' and 'Orders' for the purpose of this example:
Customers Table:
CustomerID | CustomerName | ContactName | Country |
---|---|---|---|
1 | Alfreds | Maria | Germany |
2 | Ana Trujillo | Ana | Mexico |
3 | Antonio | Antonio | Spain |
Orders Table:
OrderID | CustomerID | OrderDate |
---|---|---|
1 | 3 | 2022-12-01 |
2 | 1 | 2022-12-02 |
3 | 2 | 2022-12-03 |
To join these two tables using INNER JOIN, we would write the following SQL query:
1SELECT Customers.CustomerName AS CustomerName, Orders.OrderDate AS OrderDate 2FROM Customers 3INNER JOIN Orders 4ON Customers.CustomerID = Orders.CustomerID;
This query will return the following result:
CustomerName | OrderDate |
---|---|
Alfreds | 2022-12-02 |
Ana Trujillo | 2022-12-02 |
Antonio | 2022-12-01 |
The query combines the rows from the two tables where the value of the CustomerID
column in the 'Customers' table matches the value of the CustomerID
column in the 'Orders' table. As a result, only the rows where the CustomerID
values exist in both tables are returned, discarding all the rest of the rows.