Query:
select * from table_a where col_a = 'value1' and col_b ='value2' order by id desc limit 1
Indexes:
col_a
is indexed but col_b
is not. col_a
has a high cardinality (2M)
The entire table consists of 28M rows. No. of rows with col_a = 'value1'
is 22,000.
The latest id is 28M. The latest rows with col_a = 'value1'
has id somewhere in 25M-25.5M range.
Ideally it should scan these 22000 rows only and give us the result. But we have seen that mysql is scanning these 3M rows (28M - 25M primary key id value) and then returning the result.
Using mysql explain
we found out that PRIMARY
key is being used if the limit is set to less than 20 but after that user_id
is being prioritised.
Has anyone else seen this behaviour? Is there any flag which can be set which will avoid scanning primary key ? (we don't want to use force index(col_a_idx)
. Is there any other way which could avoid this ?