Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force an index on inner joined tables?

Tags:

How do I force indexes on a query similar to this. I need to force an index on foo and bar individually.

SELECT foo.*, bar.* FROM foo INNER JOIN bar ON foo.rel_id = bar.rel_id WHERE foo.status = 1   AND bar.status = 1 
like image 613
David Avatar asked Feb 22 '10 09:02

David


People also ask

How do I force an index in SQL?

FORCE INDEX works by only considering the given indexes (like with USE_INDEX) but in addition it tells the optimizer to regard a table scan as something very expensive. However if none of the 'forced' indexes can be used, then a table scan will be used anyway.

Do indexes work in joins?

Indexes can help improve the performance of a nested-loop join in several ways. The biggest benefit often comes when you have a clustered index on the joining column in one of the tables. The presence of a clustered index on a join column frequently determines which table SQL Server chooses as the inner table.

Do index speed up joins?

Indexes that help with a merge joinAn index on the sort keys can speed up sorting, so an index on the join keys on both relations can speed up a merge join. However, an explicit sort is often cheaper unless an index only scan can be used.

How do you create an index in alter table?

ALTER command to add and drop INDEXALTER TABLE tbl_name ADD INDEX index_name (column_list) − This adds an ordinary index in which any value may appear more than once. ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list) − This creates a special FULLTEXT index that is used for text-searching purposes.


2 Answers

Assuming index a exists on foo and index b on bar:

SELECT foo.*, bar.* FROM foo FORCE INDEX (a) INNER JOIN bar FORCE INDEX (b) ON foo.rel_id = bar.rel_id WHERE foo.status = 1   AND bar.status = 1 

would force index selection on MySql

like image 172
Ηλίας Avatar answered Sep 19 '22 12:09

Ηλίας


The obvious thing would be to create a covering index on rel_id and status of both tables to satisfy the join and where requirement.

What have you tried so-far?

edit

You provide index hints but the crux of everyone answering seems to be that you shouldn't have to do that.

From MySQL 4.0.9 on, you can also use FORCE INDEX, which acts like USE INDEX (index_list) but with the addition that a table scan is assumed to be very expensive. In other words, a table scan is used only if there is no way to use one of the given indexes to find rows in the table.

like image 29
Lieven Keersmaekers Avatar answered Sep 19 '22 12:09

Lieven Keersmaekers