I use MYSQL to create a table with combined primary key. For example, col_a and col_b are used together as the key. I will use col_a and col_b to get a row often, and also will use col_a or col_b separately to query some rows.
My questions is, how will I create the index for it? Will I need only one composite index, or three indexes with two indexes for the separated columns?
I think MYSQL will create the index for primary key. But will it create a composite index for (col_a, col_b), or create an index for each column?
Multi-Column Indexes
For a multi-column index, the index works from left to right.
Given your primary key:
(col_a, col_b)
Here are the cases where it can be used:
Given a larger index like this:
(col_a, col_b, col_c)
Covering Indexes
To utilize an index as a "covering" index, the left-to-right pattern still applies.
Given the index (col_a, col_b)
, you can select both col_a and col_b, but search only on col_a (or col_a and col_b), and MySQL can use the index both for the search and for retrieving the data because col_a and col_b are both in the index. This saves a trip to the actual row data, since the values are stored in the index.
Given the index (col_a, col_b, col_c)
, you could not SELECT col_a and col_c if you were searching only on col_a and be able to use the covering index to return col_c, since you can't skip over col_b in the index. Instead, MySQL would visit the actual table data. However, you could SELECT col_a and col_c and use it as a covering index if you were searching on both col_a and col_b.
Primary Keys in "Covering" Indexes
Every secondary index has the primary key included in the index.
A single column index, as it relates to a covering index, can be thought of as a multi-column index in the following pattern. Given the primary key (col_a, col_b)
, a single column index on col_b, really looks like this (col_b)(col_a, col_b)
.
Given the above single column index, you could still select col_a and col_b, and search on col_b, and the index could be used as a covering index. Since the primary key includes col_a, MySQL could still use the index to return both columns without having to hit the actual table data.
What if I want to search on col_b?
Given the primary key (col_a, col_b)
, if you want to search on just col_b, you should add a single column index on col_b. As described above, it can still be used as a covering index if you are returning col_b and col_a.
The composite primary key index on (col_a, col_b) will take care of situations where you are querying on both columns or querying on only col_a. For queries on only col_b, you'll need a separate index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With