The INNER JOIN keyword in SQL is used to combine rows from two or more tables based on a related column between them. It returns only the rows where there is a match in both tables.
Here’s the basic syntax for using INNER JOIN:
SELECT column1, column2, ...
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;
Explanation:
SELECT column1, column2, ...: Specifies the columns to be retrieved.FROM table1: Specifies the first table.INNER JOIN table2: Specifies the second table to be joined.ON table1.common_column = table2.common_column: Defines the condition that links the two tables, usually through a common column.
Example:
Consider two tables:
-
Employees
EmpID Name DeptID 1 Alice 101 2 Bob 102 3 Charlie 103 -
Departments
DeptID DeptName 101 HR 102 IT 104 Finance
Query using INNER JOIN:
SELECT Employees.Name, Departments.DeptName
FROM Employees
INNER JOIN Departments
ON Employees.DeptID = Departments.DeptID;
Result:
| Name | DeptName |
|---|---|
| Alice | HR |
| Bob | IT |
In this example, the INNER JOIN returns the employees who have a matching department ID in both the Employees and Departments tables. If there’s no match (like Charlie, who has no corresponding department in the Departments table), that row is not included in the result.
No comments:
Post a Comment