Do I have to create an index on columns referenced in Joins?
E.g.
SELECT
*
FROM
left_table
INNER JOIN
right_table
ON
left_table.foo = right_table.bar
WHERE
...
Should I create indexes on left_table(foo), right_table(bar), or both?
I noticed different results when I used EXPLAIN (Postgresql) with and without indexes and switching around the order of the comparison
(right_table.bar = left_table.foo)
I know for sure that indexes are used for the left of the WHERE clause but I am wondering whether I need indexes for columns listed in ON clauses.
It depends on your
wherecondition, but brief answer isyes.Usually left table would have this column as primary key which is an index by default.
The second column would be a foreign key and it is likely your queries will benefit from the index added for this column. You need to analyze your query to tell for sure if you need the index or not.
Let say the query is like this:
Index on
right_table.barwill definitely be used.On the other side:
In this case index on
right_table.barwill not be used at all, but index onleft_table.foowill.