In the previous post for this ongoing “EXPLAIN FORMAT=JSON is Cool!” series, we discussed covered indexes and how the used_columns array can help to choose them wisely. There is one more type of multiple-column indexes: composite indexes. Composite indexes are just indexes on multiple columns. Covered indexes are a subgroup of the larger set “composite indexes.” In this post, we’ll discuss how “used_key_parts” can help show which part of a multiple column key is being used.

You should prioritize using composite indexes when you have queries that search on both a set of multiple columns and a single column. For example, if you run queries like:

SELECT first_name, last_name FROM employees WHERE first_name='Steve';
SELECT first_name, last_name FROM employees WHERE first_name='Steve' and last_name like 'V%';
SELECT first_name, last_name FROM employees WHERE first_name='Steve' and last_name like 'V%' and hire_date > '1990-01-01';

It would be better to have a single index on the first_name, last_name and hire_date columns rather than three indexes on first_name, a composite on (first_name, last_name) and a composite on (first_name, last_name, hire_date). But what is the best method for testing the effectiveness of the new index?

Once again, the answer is EXPLAIN FORMAT=JSON.

To illustrate this idea, let’s add a composite index on (first_name, last_name, hire_date) to the table “employees” from the standard employees database:

It is used in all queries, and key_len is increasing–which shows that each query is using more parts of the index. But which part of index was actually used to resolve the WHERE condition, and which was used to retrieve rows?

EXPLAIN FORMAT=JSON stores this information in the used_key_parts member.

This is most likely because there are too many values in the hire_date column that satisfy the conditions, so it is easier to retrieve a data set using part of the index and then check the condition for the hire_date column.

This means that since we don’t retrieve hire_date, we can drop it from the index. We might be a bit leary as to what table rows will be accessed to perform final comparison with hire_date column, but in this case it’s fine: