Understanding Inner Join in SQL
In SQL, the INNER JOIN clause is used to combine rows from two or more tables based on a related column between them. It retrieves rows from both tables that satisfy the join condition.
Syntax
The basic syntax for an INNER JOIN in SQL is as follows:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Example
Consider the following two tables, employees
and departments
:
employees
table:
| emp_id | emp_name | dept_id |
|——–|———-|———|
| 1 | John | 101 |
| 2 | Alice | 102 |
| 3 | Bob | 101 |
departments
table:
| dept_id | dept_name |
|———|———–|
| 101 | HR |
| 102 | IT |
To retrieve the names of employees along with their department names, you can use the INNER JOIN as follows:
SELECT employees.emp_name, departments.dept_name
FROM employees
INNER JOIN departments
ON employees.dept_id = departments.dept_id;
This will produce the result: | emp_name | dept_name | |———-|———–| | John | HR | | Alice | IT | | Bob | HR |
In this example, the INNER JOIN combines the employees
and departments
tables based on the dept_id
column, and retrieves the matching rows from both tables based on the common department ID.
With INNER JOIN, you can effectively retrieve only the rows for which there is a match in both tables, based on the specified condition.
For more information on the INNER JOIN clause in SQL, refer to the official MySQL documentation.
This is a simple explanation on how to use the INNER JOIN clause in SQL to combine data from multiple tables based on a related column. ```