How to use a JOIN statement in MySQL
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.
Types of JOIN statements
There are four major types of JOINs in SQL:
- Inner Join: Selects records from Table 1 and Table 2 where the join condition is satisfied.
- Right Outer Join: Selects all the records from Table 2, and records from Table 1 for which the join condition is satisfied.
- Left Outer Join: Selects all the records from Table 1, and records from Table 2 for which the join condition is satisfied.
- Full Outer Join: Selects all the records from Table 1 and Table 2 regardless of whether the join condition is satisfied or not.
Syntax
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;
Examples
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 types
Here are some queries demonstrating different types of JOINs on these tables:
-
InnerJoin: This query is selecting rows from both the tables (Students s, Departments d) where the condition
s.DeptID = d.DeptIDis 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.DeptIDfrom the right table (Departments d). Notice the last row in the generated result, where the row forstuID = 6has been generated even though there is no matching entry fors.DeptID = d.DeptIDforstuID = 6when 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.DeptIDfrom the left table (Students s). Notice the last row in the generated result, where the row forDeptID = 4has been generated even though there is no matching entry fors.DeptID = d.DeptIDforDeptID = 4when taking the JOIN of these tables. -
FullJoin: In MySQL, there are no
FULL JOINSbut we can emulate them, by taking aUNIONof both theLEFT JOINand theRIGHT JOIN. The generated results would essentially include both the extra rows, as were generated in theRIGHT JOINandLEFT JOINsince we are taking aUNIONof both those.
SELECT stuID, First, Last, NameFROM Students sINNER JOIN Departments dON s.DeptID = d.DeptID;
Free Resources