INNER JOIN in SQL
Joins in SQL are used to combine rows from two or more tables based on a related column between them.
The most common types of joins are:
- INNER JOIN,
- LEFT JOIN,
- RIGHT JOIN, and
- FULL OUTER JOIN
The INNER JOIN keyword selects records that have matching values in both tables.
SQL Syntax
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Or alternatively,
SQL Syntax
SELECT columns
FROM table1
JOIN table2
ON table1.column_name = table2.column_name;
FROM table1
JOIN table2
ON table1.column_name = table2.column_name;
Note: Using JOIN without specifying the type of join defaults to an INNER JOIN.
Example: Let's use two tables: employees and departments.
SQL
-- Creating the employee table
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
department_id INT
);
-- Inserting the provided data
INSERT INTO employees
VALUES
(1, 'Ashish', 1),
(2, 'Rahul', 2),
(3, 'Priya', 1),
(4, 'Sneha', 3),
(5, 'Shweta', 4); Table: employees
| Employee ID | First Name | Department ID |
|---|---|---|
| 1 | Ashish | 1 |
| 2 | Rahul | 2 |
| 3 | Priya | 1 |
| 4 | Sneha | 3 |
| 5 | Shweta | 4 |
SQL
-- Creating the departments table
CREATE TABLE departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(50)
);
-- Inserting the provided data
INSERT INTO departments
VALUES
(1, 'Sales'),
(2, 'Marketing'),
(3, 'HR'); Table: departments
| Department_ID | Department_Name |
|---|---|
| 1 | Sales |
| 2 | Marketing |
| 3 | HR |
SQL
SELECT e.employee_id, e.first_name, e.department_id, d.department_name
FROM employees e
Inner JOIN departments d ON e.department_id = d.department_id;
FROM employees e
Inner JOIN departments d ON e.department_id = d.department_id;
The above query returns the following result:
| Employee_ID | First_Name | Department_ID | Department_Name |
|---|---|---|---|
| 1 | Ashish | 1 | Sales |
| 2 | Rahul | 2 | Marketing |
| 3 | Priya | 1 | Sales |
| 4 | Sneha | 3 | HR |