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:

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;

Or alternatively,

SQL Syntax

SELECT columns
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 IDFirst NameDepartment ID
1Ashish1
2Rahul2
3Priya1
4Sneha3
5Shweta4

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_IDDepartment_Name
1Sales
2Marketing
3HR

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;

The above query returns the following result:

Employee_IDFirst_NameDepartment_IDDepartment_Name
1Ashish1Sales
2Rahul2Marketing
3Priya1Sales
4Sneha3HR