If I didnât use the USE INDEX, I had a few issues as well as performance degradation in my use-case.
Let me describe my use-case with an example, I have two separate indexes with different orders. With respect to the parameter in the request, I have to choose the right index.
Following are the indexes I have:
CREATE INDEX idx_user_atm_1 ON bank-data
(user_id,atm_id) WHERE type = âtransaction_docâ;
CREATE INDEX idx_user_atm_2 ON bank-data
(user_id,atm_id) WHERE type = âtransaction_docâ;
CREATE INDEX idx_atm_1 ON bank-data
(atm_id) WHERE type = âtransaction_docâ;
CREATE INDEX idx_atm_2 ON bank-data
(atm_id) WHERE type = âtransaction_docâ;
I have a transaction list API to get transactions with filter atm_id and user_id. The following are the three use-cases I need to handle.
Case 1. With atm_id filter, the query will be
SELECT user_id, atm_id, date, amount FROM `bank-data` USE INDEX( idx_atm_1 ,idx_atm_2) WHERE atm_id=$atmId AND type = âtransaction_docâ;
Case 2. With user_id filter, the query will be
SELECT user_id, atm_id, date, amount FROM `bank-data` USE INDEX( idx_user_atm_1 ,idx_user_atm_2) WHERE user_id=$userId AND type = âtransaction_docâ;
Case 3. With atm_id and user_id filter, the query will be
SELECT user_id, atm_id, date, amount FROM `bank-data` USE INDEX( idx_user_atm_1 ,idx_user_atm_2) WHERE user_id=$userId AND atm_id=$atmId AND type = âtransaction_docâ;
Case4. Without any filters, the query will be
SELECT user_id, atm_id, date, amount FROM `bank-data` USE INDEX( idx_atm_1 ,idx_atm_2) WHERE type = âtransaction_docâ;
If I didnât use the USE INDEX, the problems I faced are:
- Case 4 will take both indexes alternatively.
- The pagination fails with duplicate entries.
- Query taking too much time to execute