r/SQL • u/BrilliantLeast7083 • Mar 25 '26
Discussion When to use RIGHT JOIN instead of switching tables in Left Join
Hello all! I need some help with understanding the utility of Right join. I have 2 tables: Orders and Customers. If I write Orders RIGHT JOIN Customers it returns the same results as switching tables and using left join, like Customers LEFT JOIN Orders. But when these 2 examples can give different results? Like when it is mandatory to use right join instead of just switching tables in left join?
35
Upvotes
263
u/Kant8 Mar 25 '26
if you have to use right join you publically announce that you started writing your query from wrong table
so just rewrite it correctly.
3
u/molodyets Mar 26 '26
left joins are for working
right joins are for answering the question "tell me all the join types" in interviews
45
u/easternsauce96 Mar 25 '26
Functionally it's the same. General consensus is to strive to use left joins as it's more intuitive to understand. Right joins can be useful when extending an already complicated query, but you would usually rewrite to use left join if possible.
56
u/government_ Mar 25 '26
Hereâs the thing, you donât. Just do a left join.
11
u/AnAimlessNomad Mar 25 '26
âWhen to use right joinâŠâ the answer is always never.
9
u/Eleventhousand Mar 25 '26
The issue with your example is that your database probably doesn't have any orders that do no have a customer. Because, who would get the ordered shipped to them.
An example where they would behave differently would be with a university having a Students table and a HomeworkAssignments table. You will have some students that are not assigned homework. If you left joined HomeworkAssignments to Students, you would see all Students, regardless if they have homework. If you switched that to a right join, you would see all HomeworkAssignments - even those that haven't been assigned out yet.
8
u/Yavuz_Selim Mar 25 '26
If there is a right join in the code that I need to manage, that right join will be rewritten to a left join.
The right join should not have been invented.
4
u/kremlingrasso Mar 25 '26
We had a guy at our company who used a right join... Yeah he doesn't work here any more.
3
u/SnooSprouts4952 Mar 25 '26
Do you want NULLs in your left columns? This is how you get NULLs in your left columns. /s
It is usually pretty easy to toss in a proper left join unless you didn't plan ahead and it is the primary table for all tables below it, in which case... do it correctly with a left join because someone is going to ask which customer ordered 25 widgets in January at some point.
3
u/greglturnquist Mar 25 '26
My $0.02.
5
u/ComicOzzy sqlHippo Mar 25 '26
You're never required to use RIGHT JOIN, but there are scenarios involving 3 or more joined tables where you are faced with the choice of writing a subquery, using nested join syntax, or using a RIGHT JOIN. Everyone hates on RIGHT JOIN for literally no reason other than they refuse to get their head around thinking in a direction other than the one they are most comfortable in.
4
u/MasterBathingBear Mar 25 '26
It is never mandatory, but we will make fun of anyone that uses a right join ever.
2
u/GaTechThomas Mar 26 '26
In 30+ years of SQL dev, I don't recall ever writing a RIGHT JOIN.
2
u/hircine1 Mar 26 '26
Not used once in 25 years. I never understood the problem it was solving. Switching tables in left joins is the way.
2
u/ThirdRateAl Mar 29 '26
Throwing in my two cents, when learning SQL I was taught that a right join is a poorly planned out left join. Functionally they are the same thing in different directions, just require more brain power to force yourself to think it through. Think about trying to perform a task only vy looking at a video that is mirrored- it's not impossible, it just requires you to think about it a lot harder than if you were just doing it.
In your example, you should get different results if you keep the tables in the same order but change the direction of the join. IE- [Orders] right join [Customers] vs [Orders] left join [Customers]. The way you have it written it should return the same results since you also change the table order. Think "X > Y" is the same as "Y < X" but "X > Y" is not the same as "X < Y." Hope that helps!
1
u/GennadiosX Mar 25 '26
When you prefer writing from right to left. Can't think of another valid reason
1
u/No-Theory6270 Mar 25 '26
I never used one
1
u/mecartistronico Mar 25 '26
RIGHT JOIN means "the main table is not the one I thought of first". So it usually doesn't happen.
In 16 years of working with SQL in a big company, I've only seen it used once (not by me). It was understandable for the specific use case, they had been building CTEs or views in a somewhat complex way, to create a dataset that... was actually complimentary to the main dataset. But still it could have been rewritten to be a LEFT JOIN.
1
u/ShyRedditFantasy Mar 25 '26
What's a right join? LOL
They teach you about right joins in school but once you start working, seeing a right join is like winning the jackpot lottery.
1
u/GTS_84 Mar 25 '26
The only time I ever use right join is when I have a list I need to exclude a bunch of entries from, and the exclusion criteria are complicated enough and join to enough other tables that the easiest way to do it is build the list of items I want to exclude with inner joins and left joins, and then as a final step do a right join and a Where to exclude NULL values.
Which is to say like... once or twice year.
And even then you could do it with sub queries or CTE's or something if you really wanted. It's never required to use right joins and I know plenty of people who never do.
1
u/No_Resolution_9252 Mar 26 '26
You do it when the the opposite side of the join has far fewer records the inside side of the join;
So in your example, if you are querying for a very small number of orders across a large number of customers, the optimizer will optimize the query more efficiently than if it were done the other way with a left join. This would be an unusual usage scenario however.
Its more common for doing things like looking for outstanding invoices.
Anyone that has a problem with a right join is stupid. It has use cases that are objectively better than doing a left join, but they are rare. I find a use case maybe just a few times a year.
1
u/dorkyitguy Mar 26 '26
The only time Iâve seen a right outer join is in machine generated code
1
u/DisastrousSecurity52 Mar 26 '26
When your junior analyst needs to stop blindly borrowing your code and write their own, you start doing some crazy things.
1
u/Learner__2022 Mar 26 '26
Use venn diagram when you are confused on joins.
1
u/DarlanSandro Sep 23 '26
Na minha opinião sua observação esta correta. Na pråtica, Pedidos RIGHT JOIN Clientes e Clientes LEFT JOIN Pedidos geram exatamente o mesmo resultado.
Não existe nenhum cenårio onde seja obrigatório usar o RIGHT JOIN ou onde ele vå gerar um resultado diferente do LEFT JOIN com as tabelas invertidas. O motor do banco de dados processa ambas as instruçÔes da mesma forma.
O RIGHT JOIN existe no SQL mais por uma questĂŁo de simetria da linguagem. Se criaram o comando para olhar para a tabela da esquerda, fazia sentido ter o equivalente para a tabela da direita.
A Ășnica utilidade prĂĄtica dele no dia a dia acontece em consultas muito grandes, com vĂĄrios JOINs encadeados. Imagine que vocĂȘ jĂĄ escreveu uma query com 5 ou 6 tabelas ligadas por INNER JOIN e LEFT JOIN. De repente, vocĂȘ precisa incluir uma nova tabela no final do cĂłdigo, mas a lĂłgica de negĂłcio exige que essa nova tabela seja a "mandante" (ou seja, vocĂȘ quer todos os registros dela, tendo ou nĂŁo correspondĂȘncia com o bloco anterior).
Nesse caso muito especĂfico, usar um RIGHT JOIN no final do cĂłdigo evita que vocĂȘ tenha que reestruturar toda a ordem do FROM e dos JOINs anteriores.
Ainda assim, a convenção não escrita no mercado é usar quase sempre o LEFT JOIN. Nós lemos de cima para baixo e da esquerda para a direita, então estruturar a query colocando a tabela principal no FROM e ir puxando as outras com LEFT JOIN torna o código muito mais fåcil de ler e dar manutenção.
Eu diria que vocĂȘ pode continuar invertendo as tabelas e usando LEFT JOIN sem medo. VocĂȘ nĂŁo estĂĄ perdendo nenhum recurso exclusivo do banco ao fazer isso.