[Solved] Optimize slow SQL query using indexes

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 `area_names` ADD INDEX `area_names_idx_id` (`id`);
ALTER TABLE `classifieds` ADD INDEX `classifieds_idx_confirmed_country_date_creat` (`confirmed`,`country`,`date_created`);
ALTER TABLE `classifieds` ADD INDEX `classifieds_idx_date_created` (`date_created`);
ALTER TABLE `classifieds_pix` ADD INDEX `classifieds_pix_idx_picture_no` (`picture_no`);
ALTER TABLE `quarter_names` ADD INDEX `quarter_names_idx_id` (`id`);
ALTER TABLE `zip_codes` ADD INDEX `zip_codes_idx_area_id_zip_id` (`area_id`,`zip_id`);
The optimized query:
SELECT
        cl_id,
        cl_title,
        cl_text,
        cl_price,
        cl_url,
        cl.cl_id AS ad_id,
        cl_cat_id,
        pix.file_name,
        area.area_name,
        qn.quarter_name 
    FROM
        (SELECT
            cl.ID AS cl_id,
            cl.title AS cl_title,
            cl.text AS cl_text,
            cl.price AS cl_price,
            cl.URL AS cl_url,
            cl.cat_id AS cl_cat_id,
            cl.zip_id AS cl_zip_id 
        FROM
            classifieds cl 
        WHERE
            cl.confirmed = 1 
            AND cl.country = 'DE' 
            AND cl.date_created <= NOW() - INTERVAL 1 DAY 
        ORDER BY
            cl.date_created DESC LIMIT 7) cl 
    INNER JOIN
        classifieds_pix pix 
            ON cl.cl_id = pix.classified_id 
            AND pix.picture_no = 0 
    INNER JOIN
        zip_codes zip 
            ON cl.cl_zip_id = zip.zip_id 
            AND zip.area_id = 132 
    INNER JOIN
        area_names area 
            ON zip.area_id = area.id 
    LEFT JOIN
        quarter_names qn 
            ON zip.quarter_id = qn.id 
    WHERE
        1 = 1 
        AND 1 = 1 
        AND 1 = 1 LIMIT 7

Related Articles



* original question posted on StackOverflow here.