There's a big discussion going on at my office on the order of the joined columns in a sql join. I'm finding it hard explaining it so I'll just present the two sql statements. Which one is better taking into account sql best practices?
SELECT a.Au_id
FROM AUTHORS a
INNER JOIN TITLEAUTHOR ta
ON a.Au_id = ta.Au_id
INNER JOIN TITLES t
ON ta.Title_id = t.Title_id
WHERE t.Title LIKE ‘%Computer%’
OR
SELECT a.Au_id
FROM AUTHORS a
INNER JOIN TITLEAUTHOR ta
ON ta.Au_id = a.Au_id
INNER JOIN TITLES t
ON t.Title_id = ta.Title_id
WHERE t.Title LIKE ‘%Computer%’
So, in a join, in the ON part, does it matter whether you write A.x = B.y or B.y = A.x
?
No, it doesn't matter.
Basically, join order DOES matter because if we can join two tables that will reduce the number of rows needed to be processed by subsequent steps, then our performance will improve.
For INNER joins, no, the order doesn't matter. The queries will return same results, as long as you change your selects from SELECT * to SELECT a.
The best practice here is to choose one and stick with it within the team. Personally, I prefer the FROM a JOIN b ON b.col = a.col
because it seems cleaner to me.
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