Mysql – Optimal indexing for SELECT (thesql)

database-designindex-tuningMySQL

What indexes would you recommend for the following select (and why)? Keep in mind there can be tens of millions of rows.

SELECT * FROM mytable WHERE md5 = ? AND created_at >= ? AND created_at <= ? LIMIT 200

Where:

  • md5 = CHAR(32)
  • created_at = DATETIME

The question is: what indexes would you add?

Best Answer

SUGGESTION #1

Based on the WHERE clause, I highly recommend a compound index

ALTER TABLE mytable ADD INDEX (md5,created_at);

That way, all parts of the WHERE clause are answered by the index.

SUGGESTION #2

Since you are imposing a limit of 200, collect the 200 keys first, then join the keys

SELECT B.* FROM
(
    SELECT id FROM mytable
    WHERE md5 = ?
    AND created_at >= ?
    AND created_at <= ? LIMIT 200
) A INNER JOIN mytable B USING (id);

I have suggested this technique before in StackOverflow

GIVE IT A TRY !!!