[Solved] Why does this MySQL query slow down when more conditions are added?

How to optimize this SQL query?

In case you have your own slow SQL query, you can optimize it automatically here.

For the query above, the following recommendations will be helpful as part of the SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
  2. Sort and Limit Before Joining (modified query below): In cases where the joins aren't filtering any rows, it's possible to sort and limit the amount of rows using a subquery in the FROM clause, before applying the joins to all other tables.
Optimal indexes for this query:
ALTER TABLE `adstable` ADD INDEX `adstable_idx_adacti_approv_target_target_adbudg` (`adactive`,`approved`,`targetdesktop`,`targetwindows`,`adbudget`);
ALTER TABLE `adstable` ADD INDEX `adstable_idx_imp_today` (`imp_today`);
ALTER TABLE `userstable` ADD INDEX `userstable_idx_balance` (`balance`);
The optimized query:
            adstable.adid AS adstable_adid,
            adstable.user AS adstable_user 
            adstable.adactive = 1 
            AND adstable.approved = 1 
            AND adstable.targetdesktop = 1 
            AND adstable.targetwindows = 1 
            AND adstable.adbudget > 0.02 
        ORDER BY
            adstable.imp_today ASC LIMIT 1) AS adstable 
            ON (
                adstable.adstable_user = userstable.id
        1 = 1 
        AND 1 = 1 
        AND 1 = 1 
        AND 1 = 1 
        AND 1 = 1 
        AND userstable.balance > 0.02 LIMIT 1

Related Articles

* original question posted on StackOverflow here.