First, what do JOIN and RIGHT JOIN do?
The JOIN
gets information from two tables and joins them according to rules you specify in the ON
or WHERE
clauses.
The JOIN
modifiers, such as LEFT
, INNER
, OUTER
and RIGHT
control the behavior you JOIN
will have in case of unmatched records -- when no record in A matches a record in B according to the specified rules, and vice-versa.
To understand this part, take table A as being the left table and table B as being the right one. When you have multiple joins, the right table in each join is the one whose name is immediately right of the JOIN
command.
e.g. FROM a1 LEFT JOIN ... LEFT JOIN b
The b
table is the right one and whatever comes before is the left one.
This is a summary of the modifiers' behavior:
LEFT
: preserves unmatched records in the left table, discards those in the right table;
RIGHT
: preserves unmatched records in the right table, discards those in the left table;
INNER
: preserves only the records that are matched, discards unmatched from both tables;
OUTER
or FULL
: preserves all records, regardless of matches.
What is visually happening?
Imagine you have two simple tables with the same names of the ones you put in there.
sold_subjects subjects
subject subject
1 1
2 4
3 5
4 6
When you RIGHT JOIN
two tables, you create a third one that looks like this:
joined_table
sold_subjects.subject subjects.subject
1 1
4 4
NULL 5
NULL 6
Please note that the subjects 2
and 3
are already gone in this subset.
When you add a WHERE
clause with sold_subjects.subject IS NULL
, you are only keeping the last two lines where there was no match in subjects.