MySQL performance tuning for DELETE query

Cbpro Ads :

Can any one help me to re-write the query to speed up the execution time? It took 37 seconds to execute.

DELETE FROM storefront_categories 
WHERE userid IN (SELECT userid 
                FROM MASTER 
                where expirydate<'2020-2-4' 
                )

At the same time, this query took only 4.69 seconds only to execute.

DELETE FROM storefront_categories 
WHERE userid NOT IN (SELECT userid FROM MASTER)

The table storefront_categories have 97K records where as in MASTER have 40K records. We have created a index on MASTER.expirydate field.

GMB :

The query looks fine as it is.

I would suggest the following indexes for optimization:

master(expiry_date, userid)
storefront_categories(userid)

The first index is a covering index for the subquery on master: it means that the database should be able to execute the subquery by looking at the index only (whereas with just expiry_date in the index, it still needs to look at the table data to fetch the related userid).

The second index lets the database optimize the in operation.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=8447&siteId=1