About Lesson
SQL INNER JOIN
The INNER JOIN
keyword selects records that have matching values in both tables.
Syntax
SELECT columns
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;
Example: INNER JOIN
SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments
ON employees.department_id = departments.id;
This query selects employee names and their corresponding department names where there is a match between the department_id
in the employees
table and the id
in the departments
table.
Sample Tables
Consider the following two tables:
Employees Table
| id | name | department_id |
|----|-------------|---------------|
| 1 | John Doe | 1 |
| 2 | Jane Smith | 2 |
| 3 | Mike Johnson| 1 |
| 4 | Emily Davis | 3 |
Departments Table
| id | department_name |
|----|-----------------|
| 1 | HR |
| 2 | Sales |
| 3 | IT |
| 4 | Marketing |
Result of INNER JOIN
| name | department_name |
|-------------|-----------------|
| John Doe | HR |
| Mike Johnson| HR |
| Jane Smith | Sales |
| Emily Davis | IT |
Only employees with a matching department_id
in the departments
table are returned.
Join the conversation