We use cookies to enhance your experience on the site
CodeWorlds

RIGHT JOIN - the mirror image

The bridge can also be crossed the other way. RIGHT JOIN is the mirror image of

LEFT JOIN
.

What RIGHT JOIN does

A RIGHT JOIN B
keeps all rows from the table on the right side (
B
), and from the left (
A
) it adds only matched rows. Where there is no pair - NULL on the left.

1SELECT a.nazwisko, k.tytul
2FROM ksiazki k
3RIGHT JOIN autorzy a ON k.autor_id = a.id;

This will show all authors, even those who do not yet have a single book on the shelf. The table on the right (

autorzy
) is "protected" - none of its rows will disappear.

RIGHT JOIN is LEFT JOIN reversed

In practice

LEFT JOIN
is used more often. Every
RIGHT JOIN
can be turned into a
LEFT JOIN
by swapping the tables:

1-- these two queries give the same result
2SELECT a.nazwisko, k.tytul
3FROM ksiazki k RIGHT JOIN autorzy a ON k.autor_id = a.id;
4
5SELECT a.nazwisko, k.tytul
6FROM autorzy a LEFT JOIN ksiazki k ON k.autor_id = a.id;

What was on the right we put on the left - and it stays "protected" just the same. That is why many scribes stick to

LEFT JOIN
only, always "protecting" the table written first.

Remember

  • LEFT JOIN - protects the table on the left (
    FROM
    ).
  • RIGHT JOIN - protects the table on the right (
    JOIN
    ).

Both add NULL where there is no pair. The choice depends only on which side we want to keep in full.

Go to CodeWorlds