[Solved] Improve SQL with WHERE sub query

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. Avoid Correlated Subqueries (query line: 33): A correlated subquery is a subquery that contains a reference (column: country_id) to a table that also appears in the outer query. Usually correlated queries can be rewritten with a join clause, which is the best practice. The database optimizer handles joins much better than correlated subqueries. Therefore, rephrasing the query with a join will allow the optimizer to use the most efficient execution plan for the query.
  2. 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.
Optimal indexes for this query:
ALTER TABLE `catcontents` ADD INDEX `catcontents_idx_category_id` (`category_id`);
ALTER TABLE `content` ADD INDEX `content_idx_content_id` (`content_id`);
ALTER TABLE `countries` ADD INDEX `countries_idx_country_id` (`country_id`);
ALTER TABLE `weblinks` ADD INDEX `weblinks_idx_content_id_weblink_or_weblink_id` (`content_id`,`weblink_ordering`,`weblink_id`);
ALTER TABLE `weblinks` ADD INDEX `weblinks_idx_weblink_orderin_weblink_id` (`weblink_ordering`,`weblink_id`);
The optimized query:
SELECT
        c.content_name,
        c.content_telephone,
        c.content_address1(SELECT
            w.weblink_url 
        FROM
            weblinks w 
        WHERE
            w.content_id = c.content_id 
        ORDER BY
            w.weblink_ordering,
            w.weblink_id ASC LIMIT 1) AS content_url,
        (SELECT
            country_name 
        FROM
            countries 
        WHERE
            countries.country_id = c.country_id LIMIT 1) AS country_name,
        (SELECT
            country_iso 
        FROM
            countries 
        WHERE
            countries.country_id = c.country_id LIMIT 1) AS country_iso 
    FROM
        catcontents cc 
    LEFT JOIN
        content c 
            ON c.content_id = cc.content_id 
    WHERE
        cc.category_id = 7 
        AND (
            SELECT
                country_iso 
            FROM
                countries 
            WHERE
                countries.country_id = c.country_id LIMIT 1
        ) = 'uk' 
    ORDER BY
        cc.catcontent_ordering ASC,
        c.content_name ASC

Related Articles



* original question posted on StackOverflow here.