Mysql – Multiple and single indexes

databaseindexingMySQLsql

I'm kinda ashamed of asking this since I've been working with MySQL for years, but oh well.

I have a table with two fields, a and b. I will be running the following queries on it:

  • SELECT * FROM ... WHERE A = 1;
  • SELECT * FROM ... WHERE B = 1;
  • SELECT * FROM ... WHERE A = 1 AND B = 1;

From the performance point of view, is at least one of the following configurations of indexes slower for at least one query? If yes, please elaborate.

  1. ALTER TABLE ... ADD INDEX (a); ALTER TABLE ... ADD INDEX (b);
  2. ALTER TABLE ... ADD INDEX (a, b);
  3. ALTER TABLE ... ADD INDEX (a); ALTER TABLE ... ADD INDEX (b); ALTER TABLE ... ADD INDEX (a, b);

Thanks (note that we are talking about non unique indexes)

Best Answer

Yes, at least one case is considerably slower. If you only define the following index:

ALTER TABLE ... ADD INDEX (a, b);

... then the query SELECT * FROM ... WHERE B = 1; will not use that index.

When you create an index with a composite key, the order of the columns of the key is important. It is recommended to try to order the columns in the key to enhance selectivity, with the most selective columns to the left-most of the key. If you don't do this, and put a non-selective column as the first part of the key, you risk not using the index at all. (Source: Tips on Optimizing SQL Server Composite Index)