is the covering index is a specific index?
Yes, it is an index purposefully designed to satisfy particular queries.
For this query
select id, name, age from table where id = 1
the covering index is a multicolumn index on (id, name, age)
created by
create index idx_name_age on table(id, name, age)
How so?
id
is the first column in the index because it's used in WHERE id = 1
. It's first because MySQL indexes are generally BTREEs, randomly accessible in index order. So WHERE id = 1
can jump, in the index, to find those id
values.
name
and age
also appear in the index because they appear in the SELECT
clause. Because they are in the index, the query can be satisfied entirely from the index. This is good because it cuts down on reads from disk or ssd: MySQL doesn't have to use the index to find rows in the main table before it can satisfy the query.
An index on only (id, name)
is not a covering index for the above query; the age
column is missing.
This query
select id, name from table where id = 1
can also be satisfied from the (id, name, age)
covering index. It also can be satisfied by an index on (id, name)
: that is a covering index for the second query (but not the first).
Your example illustrates of the glossary definition. Indexes gain query performance by using extra disk/ssd space to store data.
A Microsoft SQL Server user can declare an index like this:
create index idx_name_age on table (id) include (name, age)
In this index the values of name
and age
ride along with the id
in the index, but the index isn't ordered by those included columns. So, updating the index takes less time.
If id
is the table's primary key, none of this applies, either in MySQL's InnoDB or SQL Server. The table itself is an index on id
; it's sometimes called a clustered index. But now we're getting into too much detail.
Covering indexes can provide phenomenal increases in query performance when used wisely. Read https://use-the-index-luke.com/ For indexes to help, you must design them to match your queries. That's a large part of the art of database optimization.