24

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
1
  • 3
    Could you please explain what you mean by "forcing" an index. Do you mean create it automatically (won't work) or do you mean forcing mysql to use it (see posts below). Feb 22, 2010 at 10:20

2 Answers 2

35

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

2

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.

1
  • 1
    Totally agree, however my question is how to force indexes on an inner join.
    – David
    Feb 22, 2010 at 10:07

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.