In SQL, the JOIN
statement is used to combine row entries of two or more tables that are based on a matching column between them.
JOIN
statementsThere are four major types of JOIN
s in SQL:
In the query, we specify the SELECT
clause followed by the column(s) to select, then write the FROM
clause followed by the Table 1 name. Then comes the JOIN
clause followed by the Table 2 name. Join condition appears after that preceded by the ON
clause.
SELECT column(s)
FROM table_1
(LFET/RIGHT/INNER) JOIN table_2
ON join_condition;
We will be working with the following two tables. The relationship between the two tables is specified by the DeptID
key, which is the primary key in the Departments table and the foreign key in the Students table.
JOIN
query typesHere are some queries demonstrating different types of JOIN
s on these tables:
InnerJoin:
This query is selecting rows from both the tables (Students s, Departments d) where the condition s.DeptID = d.DeptID
is satisfied.
LeftJoin:
This query is selecting all the rows from the left table (Students s) and only the rows that satisfy the condition s.DeptID = d.DeptID
from the right table (Departments d). Notice the last row in the generated result, where the row for stuID = 6
has been generated even though there is no matching entry for s.DeptID = d.DeptID
for stuID = 6
when taking the JOIN of these tables.
RightJoin:
This query is selecting all the rows from the right table (Departments d) and only the rows that satisfy the condition s.DeptID = d.DeptID
from the left table (Students s). Notice the last row in the generated result, where the row for DeptID = 4
has been generated even though there is no matching entry for s.DeptID = d.DeptID
for DeptID = 4
when taking the JOIN of these tables.
FullJoin:
In MySQL, there are no FULL JOINS
but we can emulate them, by taking a UNION
of both the LEFT JOIN
and the RIGHT JOIN
. The generated results would essentially include both the extra rows, as were generated in the RIGHT JOIN
and LEFT JOIN
since we are taking a UNION
of both those.
SELECT stuID, First, Last, NameFROM Students sINNER JOIN Departments dON s.DeptID = d.DeptID;
Free Resources