Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I substitute a left join in SQL

Tags:

sql

left-join

Can anyone tell me how can I write the equivalent of a left join without really using left joins.

Select * from a left join b on a.name = b.name.
like image 678
Help me please Avatar asked Sep 22 '11 06:09

Help me please


People also ask

What can I use instead of left join?

While both queries are well-written, I would suggest that you always use INNER JOIN instead of listing tables and joining them in the WHERE part of the query. There are a few reasons for that: Readability is much better because the table used and related JOIN condition are in the same line.

How do you replace left join in SQL?

You can't. The conditions in the ON clause of a LEFT JOIN , when unmet, join the first table's row with null values replacing a row from the second table. If those conditions appear in the WHERE clause, they exclude the first row when unmet. This effectively converts your LEFT JOIN into an ordinary inner JOIN .

Can we replace left join with Right join?

Yes, we can. Right and left outer joins are functionally equivalent. Neither provides any functionality that the other does not, so right and left outer joins may replace each other as long as the table order is switched.


1 Answers

Bear in mind that SQL’s outer join is a kind of relational union which is expressly designed to project null values. If you want to avoid using the null value (a good thing, in my opinion), you should avoid using outer joins. Note that modern relational languages have dispensed with the concept of null and outer join entirely.

This outer join:

SELECT DISTINCT T1.id, T1.value, T2.other_value
  FROM T1
       LEFT OUTER JOIN T2
          ON T1.id = T2.id;

…is semantically equivalent to this SQL code:

SELECT T1.id, T1.value, T2.other_value
  FROM T1
       INNER JOIN T2
          ON T1.id = T2.id
UNION
SELECT T1.id, T1.value, NULL
  FROM T1
 WHERE NOT EXISTS (
                   SELECT * 
                     FROM T2
                    WHERE T1.id = T2.id
                  );

The second query may look long winded but that’s only because of the way SQL has been designed/evolved. The above is merely a natural join, a union and a semijoin. However, SQL has no semijoin operator, requires you to specify column lists in the SELECT clause and to write JOIN clauses if your product hasn’t implemented Standard SQL’s NATURAL JOIN syntax, which results in a lot of code to express something quite simple.

Therefore, you could write code such as the second query above but using an actual default value rather than the null value.

like image 112
onedaywhen Avatar answered Oct 03 '22 20:10

onedaywhen