JOIN
order can be forced by putting the tables in the right order in the FROM
clause:
-
MySQL has a special clause called
STRAIGHT_JOIN
which makes the order matter.This will use an index on
b.id
:SELECT a.Name, b.Status FROM a STRAIGHT_JOIN b ON b.ID = a.StatusID
And this will use an index on
a.StatusID
:SELECT a.Name, b.Status FROM b STRAIGHT_JOIN a ON b.ID = a.StatusID
-
Oracle has a special hint
ORDERED
to enforce theJOIN
order:This will use an index on
b.id
or build a hash table onb
:SELECT /*+ ORDERED */ * FROM a JOIN b ON b.ID = a.StatusID
And this will use an index on
a.StatusID
or build a hash table ona
:SELECT /*+ ORDERED */ * FROM b JOIN a ON b.ID = a.StatusID
-
SQL Server has a hint called
FORCE ORDER
to do the same:This will use an index on
b.id
or build a hash table onb
:SELECT * FROM a JOIN b ON b.ID = a.StatusID OPTION (FORCE ORDER)
And this will use an index on
a.StatusID
or build a hash table ona
:SELECT * FROM b JOIN a ON b.ID = a.StatusID OPTION (FORCE ORDER)
-
PostgreSQL guys, sorry. Your TODO list says:
Optimizer hints (not wanted)
Optimizer hints are used to work around problems in the optimizer. We would rather have the problems reported and fixed.
As for the order in the comparison, it doesn’t matter in any RDBMS
, AFAIK.
Though I personally always try to estimate which column will be searched for and put this column in the left (for it to seem like an lvalue
).
See this answer for more detail.