In SQL, an INNER JOIN
is used to retrieve rows from multiple tables where there is a match between the columns being joined. The INNER JOIN
keyword selects records that have matching values in both tables.
Here’s a basic structure of an INNER JOIN
:
SELECT columns FROM table1 INNER JOIN table2 ON table1.common_column = table2.common_column;
Example Scenario
Suppose you have two tables:
-
Employees
EmployeeID
FirstName
LastName
DepartmentID
-
Departments
DepartmentID
DepartmentName
To get a list of employees along with their department names, you would use an INNER JOIN
like this:
SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName FROM Employees INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
Explanation
Employees.FirstName, Employees.LastName, Departments.DepartmentName
: These are the columns you want to retrieve.FROM Employees
: This specifies the first table to retrieve data from.INNER JOIN Departments
: This specifies that you are joining theDepartments
table with theEmployees
table.ON Employees.DepartmentID = Departments.DepartmentID
: This specifies the condition for the join, which is that theDepartmentID
column in both tables must match.
Key Points
- Matching Rows:
INNER JOIN
returns only those rows where there is a match in both tables. - Multiple Joins: You can join more than two tables in a single query by chaining
INNER JOIN
clauses. - Aliases: For readability, you can use table aliases. For example:
SELECT e.FirstName, e.LastName, d.DepartmentName FROM Employees e INNER JOIN Departments d ON e.DepartmentID = d.DepartmentID;