INNER JOIN
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. If there is no match, the rows are excluded from the result set. This is the most commonly used type of join in SQL.
Key Points
- Matching Rows:
INNER JOIN
returns only the rows where there is a match in both tables. - Common Column: The tables being joined must have at least one common column, usually a primary key and foreign key.
- Exclusion of Non-Matching Rows: Rows that do not have a match in both tables are excluded from the result set.
- Alias Support: You can use table aliases to simplify queries.
Syntax
column1, column2, ...
: The columns you want to retrieve.table1, table2
: The tables you want to join.common_column
: The column that relates the two tables.
Examples
Suppose you have two tables:Employees
and Departments
.
Table: Employees
EmployeeID | Name | City | DepartmentID |
---|---|---|---|
1 | Anand | Chennai | 101 |
2 | Bala | Coimbatore | 102 |
3 | Kavitha | Karaikal | 103 |
4 | Raj | Madurai | 104 |
5 | Kumar | Trichy | 105 |
DepartmentID | DepartmentName |
---|---|
101 | HR |
102 | Finance |
103 | IT |
104 | Marketing |
105 | Sales |
Name | DepartmentName |
---|---|
Anand | HR |
Bala | Finance |
Kavitha | IT |
Raj | Marketing |
Kumar | Sales |
Using INNER JOIN with WHERE Clause
You can combineINNER JOIN
with the WHERE
clause to filter the results further. For example, retrieve employees who work in the IT department.
Name | DepartmentName |
---|---|
Kavitha | IT |
Using INNER JOIN with Multiple Tables
You can useINNER JOIN
to join more than two tables. Suppose you have an additional table named Projects
.
Table: Projects
ProjectID | ProjectName | DepartmentID |
---|---|---|
201 | Project A | 101 |
202 | Project B | 102 |
203 | Project C | 103 |
Name | DepartmentName | ProjectName |
---|---|---|
Anand | HR | Project A |
Bala | Finance | Project B |
Kavitha | IT | Project C |
Practical Use Case
Suppose you have a table namedStudents
and another table named Courses
.
Table: Students
StudentID | Name | City | CourseID |
---|---|---|---|
1 | Ram | Chennai | 101 |
2 | Karthik | Coimbatore | 102 |
3 | David | Bangalore | 103 |
CourseID | CourseName |
---|---|
101 | Mathematics |
102 | Science |
103 | English |
Name | CourseName |
---|---|
Ram | Mathematics |
Karthik | Science |
David | English |
Key Takeaways
INNER JOIN
returns only the rows where there is a match in both tables.- It is used to combine rows from two or more tables based on a related column.
- Non-matching rows are excluded from the result set.
- You can use
INNER JOIN
with theWHERE
clause to filter results further. INNER JOIN
can be used to join multiple tables in a single query.