mysql query takes too long because of wrong indexes usage

54 views Asked by At

I have the following query in mysql,

SELECT COALESCE(sum(COALESCE(amount, 0)), 0) as sum_amount,
       COALESCE(sum(COALESCE(fees_amount, 0)), 0) as sum_fees_amount
FROM incoming_operation
WHERE status = 'CLEARED' 
  and merchant_id = ? 
  and shop_id IN (?) 
  and currency = ? 
  and cycle_id is null
FOR UPDATE

where shop_id,currency,status and cycle_id are indexed

CREATE INDEX payout_operation_update ON incoming_operation(shop_id,currency,status);

CREATE INDEX cycle_id_index ON incoming_operation (cycle_id);

the value of cycle_id is mostly NULL in the DB. the values of shop_id,currency,status are unique in the DB

when running the above query, the query ran for a very long time (2 hours) and I got a lock where other operations couldnt update any row in the DB.

from running the query with explain ive seen that it used both indexes: shop_id,currency,status and cycle_id.

can i assume that using payout_operation_update(shop_id,currency,status) index only will make the query quicker?

my assumption is that because of using cycle_id_index, all other rows (whos cycle_id is null) were also locked, and using only payout_operation_update(shop_id,currency,status) index will lock only the relevant rows (those that apply to filter of shop_id,currency,status)

that's the values i got from EXPLAIN:

SIMPLE
1   
incoming_operation
index_merge 
payout_operation_update,status_expected_clear_datetime,merchant_status_expected_clear_datetime,cycle_id_index   
payout_operation_update,cycle_id_index  
361,9       
922125  
10.00
Using intersect(payout_operation_update,cycle_id_index); 
Using where

is that assumption valid?

0

There are 0 answers