Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it matter which table to select FROM and which to JOIN

Tags:

sql

join

mysql

If I'm selecting equal fields from two tables, does it matter which table to SELECT from and which to JOIN from?

I guess I'm really interested in how best to join tables. Are there guidelines for which to SELECT FROM and which to JOIN, or when it doesn't matter?

I'm working on a query that joins about 5 tables and not sure if it matters which I pull from and which I join. Currently I'm using FROM the table my WHERE clause pulls from. I assume this is the correct way, but any explanations or guidelines would be great!

Same applies for LEFT JOIN, as the feedback I see is that the default INNER JOIN does not matter.

For example

SELECT
  a.field1,
  a.field2,
  a.field3,
  b.field1,
  b.field2

choice 1:

FROM 
  a
JOIN
  b ON a.field1 = b.field1
WHERE
  a.field1 = 'abc'

Choice 2:

FROM 
  b
JOIN
  a ON b.field1 = a.field1
WHERE
  a.field1 = 'abc'
like image 820
d-_-b Avatar asked Oct 23 '25 18:10

d-_-b


1 Answers

There is a no functional difference for inner joins, but there is a functional difference for outer joins. (Does the join order matter in SQL?)

^^ A good way of picturing why is this: a left outer join between A and B is the same thing as a right outer join between B and A. Direction is very important to outer joins. In fact that is why you don't have to say the keyword 'outer' in 'left join' or 'right join', the database knows you want an outer join because otherwise there would be no point in specifying direction.

If your question is about performance, yes, there can potentially be an advantage to specifying smaller tables first, and subsequently joining into larger tables (rather than the other way around). However it's not always possible to optimize that way depending on how the tables are related.

Oracle for instance has the LEADING hint which can be used to instruct the database to start with a specified table first even though it's not the first listed in the FROM clause (http://docs.oracle.com/cd/B13789_01/server.101/b10752/hintsref.htm#30459).

like image 196
Brian DeMilia Avatar answered Oct 26 '25 06:10

Brian DeMilia