INNER Join
In SQL, an INNER JOIN
is a type of join that combines rows from two or more tables based on a specified join condition. It returns only the rows that have matching values in both tables.
The basic syntax of the INNER JOIN
is as follows:
SELECT column1, column2, ...
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
In this syntax, table1
and table2
are the two tables you want to join, and column_name
is the column in both tables that you use as the join condition. The ON
keyword is used to specify the join condition, which indicates the relationship between the tables.
Here's an example to illustrate the INNER JOIN
:
Suppose we have two tables, "Customers" and "Orders," with columns as follows:
Customers table:
CustomerID
CustomerName
Orders table:
OrderID
CustomerID
OrderDate
TotalAmount
If we want to retrieve the customer name along with order details for each order, we can use the INNER JOIN
on the CustomerID
column:
SELECT OrderID, CustomerName, OrderDate, TotalAmount
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID;
In this example, the INNER JOIN
matches the CustomerID
column in both tables and combines the relevant rows from "Customers" and "Orders" where the CustomerID
values match. This allows us to retrieve the desired information, which includes the customer name, order date, and total amount for each order.
The INNER JOIN
is the most common type of join used in SQL, and it only returns rows with matching values in both tables. Any rows that do not have a match in the other table are excluded from the result set.
It's important to note that when using INNER JOIN
, it is essential to have an appropriate and accurate join condition to ensure that the data is correctly combined. The join condition should be based on related columns in both tables to retrieve meaningful and relevant results.