🔹 INNER JOIN in SQL
Definition:
The INNER JOIN
clause is used to return rows when there is at least one match in both tables. It combines rows from two or more tables based on a related column between them.
Syntax:
SELECT table1.column, table2.column
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;
Example:
SELECT Employees.name, Departments.department_name
FROM Employees
INNER JOIN Departments
ON Employees.department_id = Departments.department_id;
Sample Employees
Table:
id | name | department_id |
1 | Alice | 101 |
2 | Bob | 102 |
3 | Charlie | 103 |
Sample Departments
Table:
department_id | department_name |
101 | HR |
102 | Engineering |
104 | Finance |
Output:
name | department_name |
Alice | HR |
Bob | Engineering |
Explanation:
The query joins the Employees
and Departments
tables using the department_id
column.
- Alice (dept 101) matches with HR
- Bob (dept 102) matches with Engineering
- Charlie (dept 103) has no match in the Departments table → **excluded**
- Finance (id 104) has no matching employee → also **excluded**
Only rows with matching keys in both tables appear in the output.
Usage Tips:
- Use
INNER JOIN
when you need to retrieve data only where there's a match in both tables.
- Make sure the joining column exists and is meaningful in both tables.
Common Mistake:
Assuming INNER JOIN
includes unmatched rows. For that, use LEFT JOIN
or RIGHT JOIN
.
📘 Note: INNER JOIN is the default join type. Writing just JOIN
means INNER JOIN.