An INNER JOIN in SQL is used to retrieve rows from two or more tables that meet a specific condition. It only includes rows where there is a match in both tables based on the join condition.
Syntax:
SELECT column1, column2, ...
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Explanation:
table1andtable2: The tables you are joining.ON: Specifies the condition that links the tables (usually a column common to both tables, such as a foreign key relationship).
Example:
Tables:
Employees
| EmployeeID | Name | DepartmentID |
|---|---|---|
| 1 | Alice | 101 |
| 2 | Bob | 102 |
| 3 | Charlie | NULL |
Departments
| DepartmentID | DepartmentName |
|---|---|
| 101 | HR |
| 102 | IT |
| 103 | Sales |
Query:
SELECT Employees.Name, Departments.DepartmentName
FROM Employees
INNER JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID;
Result:
| Name | DepartmentName |
|---|---|
| Alice | HR |
| Bob | IT |
Key Points:
- Only Matching Rows: Rows are returned only if there is a match between
table1andtable2based on theONcondition. - No Null Matches: Rows with NULL values in the columns used for the join condition are excluded.
- Alias Usage: You can use table aliases to make the query more readable:
SELECT e.Name, d.DepartmentName FROM Employees e INNER JOIN Departments d ON e.DepartmentID = d.DepartmentID;
No comments:
Post a Comment