SQL - Inner Join
In the context of databases, an inner join is a type of join operation that combines rows from two or more tables based on a related column between them. The result of an inner join includes only the rows where the values in the related column match in both tables.
To better understand how an inner join works, let's consider an example with two tables: "Customers" and "Orders":
Customers Table
ID |
Name |
Age |
1 |
John |
25 |
2 |
Jane |
30 |
3 |
Mike |
35 |
Orders Table
OrderID |
Amount |
CustID |
101 |
100.00 |
1 |
102 |
200.00 |
2 |
103 |
150.00 |
1 |
The "Customers" table contains information about customers, including their unique ID, name, and age. The "Orders" table contains information about customer orders, including the order ID, amount, and the corresponding customer ID.
Now, let's say we want to retrieve the order details along with the customer name for each order. To achieve this, we can use an inner join.
The basic syntax for an inner join is as follows:
SELECT column_list
FROM table1
INNER JOIN table2 ON table1.column = table2.column;
To retrieve the order details with customer names, we would perform the following inner join:
SELECT Orders.OrderID, Orders.Amount, Customers.Name
FROM Orders
INNER JOIN Customers ON Orders.CustID = Customers.ID;
In this example, we select the order ID and amount from the "Orders" table and the customer name from the "Customers" table. We perform an inner join between the two tables, connecting them based on the customer ID (CustID) column in the "Orders" table and the ID column in the "Customers" table.
The join condition Orders.CustID = Customers.ID ensures that only the rows with matching customer IDs between the two tables are included in the result set.
The output of the query would be:
OrderID |
Amount |
Name |
101 |
100.00 |
John |
102 |
200.00 |
Jane |
103 |
150.00 |
John |
As you can see, the result set includes the order ID, amount, and the customer name for each order. The inner join combines the matching rows from the "Orders" table and the "Customers" table based on the customer ID column, providing the desired information.
In summary, an inner join in SQL Server allows you to combine rows from two or more tables based on a related column, retrieving only the rows with matching values in both tables. It enables you to link related data from different tables and obtain a consolidated result set.