Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for the order of joined columns in a sql join?

Tags:

sql

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?

like image 730
Lieven Cardoen Avatar asked Jun 26 '14 10:06

Lieven Cardoen


People also ask

Does the order of columns in join matter?

No, it doesn't matter.

Does the order of joins matter for performance SQL?

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.

Does it matter what order you join tables in?

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.


1 Answers

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.

like image 168
Thomas Ruiz Avatar answered Oct 26 '22 13:10

Thomas Ruiz