41

I use INNER JOIN and LEFT OUTER JOINs all the time. However, I never seem to need RIGHT OUTER JOINs, ever.

I've seen plenty of nasty auto-generated SQL that uses right joins, but to me, that code is impossible to get my head around. I always need to rewrite it using inner and left joins to make heads or tails of it.

Does anyone actually write queries using Right joins?

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
KM.
  • 101,727
  • 34
  • 178
  • 212
  • Related: http://stackoverflow.com/questions/436345/when-or-why-would-you-use-a-right-outer-join-instead-of-left – Thilo Jul 28 '14 at 06:18

9 Answers9

34

In SQL Server one edge case where I have found right joins useful is when used in conjunction with join hints.

The following queries have the same semantics but differ in which table is used as the build input for the hash table (it would be more efficient to build the hash table from the smaller input than the larger one which the right join syntax achieves)

SELECT #Large.X
FROM #Small 
RIGHT HASH JOIN #Large ON #Small.X = #Large.X
WHERE #Small.X IS NULL

SELECT #Large.X
FROM #Large  
LEFT HASH JOIN #Small ON #Small.X = #Large.X
WHERE #Small.X IS NULL 

Aside from that (product specific) edge case there are other general examples where a RIGHT JOIN may be useful.

Suppose that there are three tables for People, Pets, and Pet Accessories. People may optionally have pets and these pets may optionally have accessories

CREATE TABLE Persons
  (
     PersonName VARCHAR(10) PRIMARY KEY
  );

INSERT INTO Persons
VALUES      ('Alice'),
            ('Bob'),
            ('Charles');

CREATE TABLE Pets
  (
     PetName    VARCHAR(10) PRIMARY KEY,
     PersonName VARCHAR(10)
  );

INSERT INTO Pets
VALUES      ('Rover',
             'Alice'),
            ('Lassie',
             'Alice'),
            ('Fifi',
             'Charles');

CREATE TABLE PetAccessories
  (
     AccessoryName VARCHAR(10) PRIMARY KEY,
     PetName       VARCHAR(10)
  );

INSERT INTO PetAccessories
VALUES      ('Ball', 'Rover'),
            ('Bone', 'Rover'),
            ('Mouse','Fifi');

If the requirement is to get a result listing all people irrespective of whether or not they own a pet and information about any pets they own that also have accessories.

This doesn't work (Excludes Bob)

SELECT P.PersonName,
       Pt.PetName,
       Pa.AccessoryName
FROM   Persons P
       LEFT JOIN Pets Pt
         ON P.PersonName = Pt.PersonName
       INNER JOIN PetAccessories Pa
         ON Pt.PetName = Pa.PetName; 

This doesn't work (Includes Lassie)

SELECT P.PersonName,
       Pt.PetName,
       Pa.AccessoryName
FROM   Persons P
       LEFT JOIN Pets Pt
         ON P.PersonName = Pt.PersonName
       LEFT JOIN PetAccessories Pa
         ON Pt.PetName = Pa.PetName; 

This does work (but the syntax is much less commonly understood as it requires two ON clauses in succession to achieve the desired logical join order)

SELECT P.PersonName,
       Pt.PetName,
       Pa.AccessoryName
FROM   Persons P
       LEFT JOIN Pets Pt
                  INNER JOIN PetAccessories Pa
                    ON Pt.PetName = Pa.PetName
         ON P.PersonName = Pt.PersonName;

All in all probably easiest to use a RIGHT JOIN

SELECT P.PersonName,
       Pt.PetName,
       Pa.AccessoryName
FROM   Pets Pt
       JOIN PetAccessories Pa
         ON Pt.PetName = Pa.PetName
       RIGHT JOIN Persons P
         ON P.PersonName = Pt.PersonName;

Though if determined to avoid this another option would be to introduce a derived table that can be left joined to

SELECT P.PersonName,
       T.PetName,
       T.AccessoryName
FROM   Persons P
       LEFT JOIN (SELECT Pt.PetName,
                         Pa.AccessoryName,
                         Pt.PersonName
                  FROM   Pets Pt
                         JOIN PetAccessories Pa
                           ON Pt.PetName = Pa.PetName) T
         ON T.PersonName = P.PersonName; 

SQL Fiddles: MySQL, PostgreSQL, SQL Server

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
  • 2
    If you don't understand why poor Bob has been excluded, this helped me: http://weblogs.sqlteam.com/jeffs/archive/2007/10/11/mixing-inner-outer-joins-sql.aspx – Luke Nov 28 '14 at 15:42
  • @Luke - Coincidental that we both used a "pets" example! – Martin Smith Nov 28 '14 at 18:51
  • Using right join might indeed produce nicer query in some cases when linking more than two tables. However I guess, for many people it would still be mentally easier to write a more complex LEFT query, because of the habit to start with the main dataset and then attaching the "children" data. – JustAMartin Aug 07 '21 at 16:18
  • This is a good example for the rare use cases of RIGHT JOIN, but still: you can achieve the same result (excluding "Lassie") with LEFT JOIN by adding the requirements as a WHERE condition, i.e. `WHERE PetAcessories.ID IS NOT NULL`. The execution plan will be the same, and the intention of the query more readable. – Kaii Aug 18 '21 at 21:20
26

It depends on what side of the join you put each table.

If you want to return all rows from the left table, even if there are no matches in the right table... you use left join.

If you want to return all rows from the right table, even if there are no matches in the left table, you use right join.

Interestingly enough, I rarely used right joins.

Petros
  • 8,862
  • 3
  • 39
  • 38
  • 11
    I always find it more logical to start with the table which has all of the non-orphan items, so I always end up using LEFT JOIN as well. I wonder if its a cultural thing? – Matthew Farwell Mar 27 '09 at 15:32
  • 5
    +1, left & right outer joins are exactly the same only opposite. – Nathan Koop Mar 27 '09 at 15:59
  • 1
    @MatthieuF: Maybe it is cultural. Using right join feels like doing something in an opposite way. It comes without thinking at least to me, to always arrange my joins in a way so that (if needed) left join fits the situation. I don't know why? :-) – Petros Mar 27 '09 at 17:23
  • 1
    MySQL recommends LEFT JOIN's for code portability across databases. See their section on RIGHT JOIN at http://dev.mysql.com/doc/refman/5.0/en/join.html – LWurm Oct 05 '13 at 03:30
  • 1
    Specifically Sqllite only implements LEFT JOIN and not RIGHT (or FULL) according to https://www.sqlitetutorial.net/sqlite-full-outer-join/ – Martin Smith Apr 22 '20 at 18:29
8

You usually use RIGHT OUTER JOINS to find orphan items in other tables.

Ólafur Waage
  • 68,817
  • 22
  • 142
  • 198
  • Can you please provide more detail? – Shabbyrobe Aug 28 '09 at 04:09
  • 19
    I find this answer makes right joins sound special when they're not. Left and right outer joins are mirror images of each other - both useful for finding orphaned items. The choice of which to use is simply based on which table you want all rows from, even if there are no matches. – Cory House Oct 04 '09 at 02:08
4

No, I don't for the simple reason I can accomplish everything with inner or left joins.

Eppz
  • 3,178
  • 2
  • 19
  • 26
3

I only use left, but let me say they are really the same depending how how you order things. I worked with some people that only used right, becasue they built queries from the inside out and liked to keep their main items at the bottom thus in their minds it made sense to only use right.

I.e.

Got main thing here

need more junk

More Junk right outer join Main Stuff

I prefer to do main stuff then junk... So left outer works for me.

So whatever floats your boat.

Neil N
  • 24,862
  • 16
  • 85
  • 145
Jojo
  • 319
  • 3
  • 10
2

The only time I use a Right outer join is when I am working on an existing query and need to change it (normally from an inner). I could reverse the join and make it a left and probably be ok, but I try and reduce the amount of things I change when I modify code.

kemiller2002
  • 113,795
  • 27
  • 197
  • 251
1

Our standard practice here is to write everything in terms of LEFT JOINs if possible. We've occasionally used FULL OUTER JOINs if we've needed to, but never RIGHT JOINs.

mwigdahl
  • 16,268
  • 7
  • 50
  • 64
1

You can accomplish the same thing using LEFT or RIGHT joins. Generally most people think in terms of a LEFT join probably because we read from left to right. It really comes down to being consistent. Your team should focus on using either LEFT or RIGHT joins, not both, as they are essentially the same exact thing, written differently.

Joe Phillips
  • 49,743
  • 32
  • 103
  • 159
1

Rarely, as stated you can usually reorder and use a left join. Also I naturally tend to order the data, so that left joins work for getting the data I require. I think the same can be said of full outer and cross joins, most people tend to stay away from them.

sfossen
  • 4,774
  • 24
  • 18