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.
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With