SQL INNER JOIN: The Beginner's Guide To Inner Join in SQL
SQL INNER JOIN: The Beginner's Guide To Inner Join in SQL
org/sql-inner-join/
sqltutorial.org
Summary: in this tutorial, we will show you how to use the SQL
INNER JOIN clause to query data from two or more tables.
The inner join clause links two (or more) tables by a relationship
between two columns. Whenever you use the inner join clause,
you normally think about the intersection.
Table A has four rows: (1,2,3,4) and table B has four rows:
(3,4,5,6)
When table A joins with the table B using the inner join, we have
the result set (3,4) that is the intersection of the table A and table
B.
For each row in table A, the inner join clause finds the matching
rows in the table B. If a row is matched, it is included in the final
result set.
SELECT
A.n
FROM A
INNER JOIN B ON B.n = A.n;
The INNER JOIN clause appears after the FROM clause. The
condition to match between table A and table B is specified after
the ON keyword. This condition is called join condition i.e., B.n =
A.n
The INNER JOIN clause can join three or more tables as long as
they have relationships, typically foreign key relationships.
tables: A, B, and C:
SELECT
A.n
FROM A
INNER JOIN B ON B.n = A.n
INNER JOIN C ON C.n = A.n;
emp_dept_tables
To get the information of the department id 1,2, and 3, you use the
following statement.
SELECT
department_id,
department_name
FROM
departments
WHERE
department_id IN (1, 2, 3);
See it in action
SELECT
first_name,
last_name,
department_id
FROM
employees
WHERE
department_id IN (1, 2, 3)
ORDER BY
department_id;
See it in action
To combine data from these two tables, you use an inner join
clause as the following query:
SELECT
first_name,
last_name,
employees.department_id,
departments.department_id,
department_name
FROM
employees
INNER JOIN
departments ON departments.department_id =
employees.department_id
WHERE
employees.department_id IN (1 , 2, 3);
See it in action
For each row in the employees table, the statement checks if the
value of the department_id column equals the value of the
department_id column in the departments table. If the
condition
Each employee holds one job while a job may be held by many
employees. The relationship between the jobs table and the
employees table is one-to-many.
emp_dept_jobs_tables
The following query uses the inner join clauses to join 3 tables:
employees, departments, and jobs to get the first name, last name,
job title, and department name of employees who work in
department id 1, 2, and 3.
SELECT
first_name,
last_name,
job_title,
department_name
FROM
employees e
INNER JOIN departments d ON d.department_id =
e.department_id
INNER JOIN jobs j ON j.job_id = e.job_id
WHERE
e.department_id IN (1, 2, 3);
See it in action
Now you should understand how the SQL INNER JOIN clause
works and know how to apply it to query data from multiple tables.
YesNo