[Solved] create index for select query with multiple OR conditions and AND conditions

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 OR Conditions By Using UNION (modified query below): In mosts cases, filtering using the OR operator cannot be applied using indexes. A more optimized alternative will be to split the query to two parts combined with a UNION clause, while each query holds one part of the original OR condition.
  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.
  3. Use Numeric Column Types For Numeric Values (query line: 16): Referencing a numeric value (e.g. 1234456) as a string in a WHERE clause might result in poor performance. Possible impacts of storing numbers as varchars: more space will be used, you won't be able to perform arithmetic operations, the data won't be self-validated, aggregation functions like SUM won't work, the output may sort incorrectly and more. If the column is numeric, remove the quotes from the constant value, to make sure a numeric comparison is done.
  4. Use Numeric Column Types For Numeric Values (query line: 37): Referencing a numeric value (e.g. 123456) as a string in a WHERE clause might result in poor performance. Possible impacts of storing numbers as varchars: more space will be used, you won't be able to perform arithmetic operations, the data won't be self-validated, aggregation functions like SUM won't work, the output may sort incorrectly and more. If the column is numeric, remove the quotes from the constant value, to make sure a numeric comparison is done.
  5. Use UNION ALL instead of UNION (query line: 27): Always use UNION ALL unless you need to eliminate duplicate records. By using UNION ALL, you'll avoid the expensive distinct operation the database applies when using a UNION clause.
Optimal indexes for this query:
ALTER TABLE `table1` ADD INDEX `table1_idx_id` (`id`);
ALTER TABLE `table2` ADD INDEX `table2_idx_is_test_phone2` (`is_test`,`phone2`);
ALTER TABLE `table2` ADD INDEX `table2_idx_is_test_id` (`is_test`,`id`);
The optimized query:
SELECT
        SUM(internal_id_count) 
    FROM
        ((SELECT
            COUNT(test.id) AS internal_id_count 
        FROM
            table1 
        INNER JOIN
            table2 
                ON table1.id = table2.id 
        WHERE
            (
                (
                    table2.phone2 IS NOT NULL 
                    AND table2.phone2 IN (
                        '1234456'
                    )
                )
            ) 
            AND table2.id <> 1234 
            AND table2.created_at >= '2015-10-10' 
            AND table2.status NOT IN (
                'test'
            ) 
            AND table2.is_test = 'No') 
    UNION
    DISTINCT (SELECT
        COUNT(test.id) AS internal_id_count 
    FROM
        table1 
    INNER JOIN
        table2 
            ON table1.id = table2.id 
    WHERE
        (table2.email = '[email protected]' 
        OR (table2.phone1 IS NOT NULL 
        AND table2.phone1 IN ('123456'))) 
        AND table2.id <> 1234 
        AND table2.created_at >= '2015-10-10' 
        AND table2.status NOT IN ('test') 
        AND table2.is_test = 'No')
) AS union1

Related Articles



* original question posted on StackOverflow here.