There is something I cannot understand when I try to optimize my query using index.
The table looks like this:
create table order_table (
id int not null primary key,
customer_id varchar(50) not null,
sale int not null,
key customer_sale_idx (customer_id, sale)
);
when I run explain select * from order_table where customer_id=2 order by sale limit 1;
It shows
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: order_table
partitions: NULL
type: index
possible_keys: customer_sale_idx
key: customer_sale_idx
key_len: 206
ref: NULL
rows: 5
filtered: 20.00
Extra: Using where; Using index; Using filesort
And then I add another index alter table order_table add key sale_customer_idx (sale, customer_id);
now the explain select * from order_table where customer_id=2 order by sale limit 1; query shows
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: order_table
partitions: NULL
type: index
possible_keys: customer_sale_idx
key: sale_customer_idx
key_len: 206
ref: NULL
rows: 1
filtered: 20.00
Extra: Using where; Using index
Q1: I suppose mysql should check the customer_id first, get those records that match the where, then do the sort by sale. It uses the customer_sale_idx index as I expected, but I don't konw why it use Using filesort rather than utilize the cover index
(customer_id, sale) to do the sort.
Q2: MySQL uses the new index sale_customer_idx (sale, customer_id) after I added it. But I don't understand how this index helps to get rid of the Using filesort.
Q3: The latter explain says there is only one possible_keys which is customer_sale_idx, but then it use sale_customer_idx. How?
BTW,I know it's strange that customer_id is varchar. But let's just focus on explaining this phenomenon.