[Solved] ORDER BY datetime makes the query very slow

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 `accounts` ADD INDEX `accounts_idx_status_do_call` (`status`,`do_not_call`);
ALTER TABLE `call_codes` ADD INDEX `call_codes_idx_call_id` (`call_code_id`);
ALTER TABLE `industries` ADD INDEX `industries_idx_industry_id` (`industry_id`);
ALTER TABLE `phone_calls` ADD INDEX `phone_calls_idx_status_owner_id_trigger_on` (`status`,`owner_id`,`trigger_on`);
ALTER TABLE `phone_calls` ADD INDEX `phone_calls_idx_trigger_on` (`trigger_on`);
The optimized query:
SELECT
        callSubject AS callSubject,
        ac.account_name AS accountName,
        DATE_FORMAT(ph_trigger_on,
        "%c/%e/%Y %h:%i %p") AS triggerOn,
        ind.name AS industry,
        cc.call_code_name AS callCode 
    FROM
        (SELECT
            ph.call_subject AS callSubject,
            ph.trigger_on AS ph_trigger_on,
            ph.account_id AS ph_account_id,
            ph.call_code_id AS ph_call_code_id 
        FROM
            phone_calls AS ph 
        WHERE
            ph.status = 1 
            AND ph.owner_id = 1 
            AND ph.trigger_on BETWEEN '2012-11-19 00:00:00' AND '2013-03-19 23:59:59' 
        ORDER BY
            ph.trigger_on ASC LIMIT 1000) AS ph 
    INNER JOIN
        accounts AS ac 
            ON ph.ph_account_id = ac.account_id 
    INNER JOIN
        industries AS ind 
            ON ind.industry_id = ac.industry_id 
    INNER JOIN
        call_codes AS cc 
            ON ph.ph_call_code_id = cc.call_code_id 
    WHERE
        ac.status = 1 
        AND 1 = 1 
        AND 1 = 1 
        AND ac.do_not_call = 0 
        AND 1 = 1 LIMIT 1000

Related Articles



* original question posted on StackOverflow here.