[Solved] Very weird result of CTEs and subqueries

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 Subqueries (query line: 27): We advise against using subqueries as they are not optimized well by the optimizer. Therefore, it's recommended to join a newly created temporary table that holds the data, which also includes the relevant search index.
  2. Explicitly ORDER BY After GROUP BY (modified query below): By default, the database sorts all 'GROUP BY col1, col2, ...' queries as if you specified 'ORDER BY col1, col2, ...' in the query as well. If a query includes a GROUP BY clause but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying 'ORDER BY NULL'.
The optimized query:
WITH t1 AS (SELECT
        a.id,
        AVG(standard_qty) std_avg,
        AVG(poster_qty) pos_avg,
        AVG(glossy_qty) gloss_avg 
    FROM
        accounts a 
    JOIN
        orders o 
            ON a.id = o.account_id 
    GROUP BY
        1 
    ORDER BY
        NULL), t2 AS (SELECT
        MAX(t1.std_avg) max_std_avg,
        MAX(t1.pos_avg) max_pos_avg,
        MAX(t1.gloss_avg) max_gloss_avg 
    FROM
        t1) SELECT
        std_id,
        t2.max_std_avg,
        pos_id,
        t2.max_pos_avg,
        glos_id,
        t2.max_gloss_avg 
    FROM
        (SELECT
            (SELECT
                t1.id std_id 
            FROM
                t1,
                t2 
            WHERE
                t1.std_avg = t2.max_std_avg),
            (SELECT
                t1.id pos_id 
            FROM
                t1,
                t2 
            WHERE
                t1.pos_avg = t2.max_pos_avg),
            (SELECT
                t1.id glos_id 
            FROM
                t1,
                t2 
            WHERE
                t1.gloss_avg = t2.max_gloss_avg)) foo,
            t1,
            t2

Related Articles



* original question posted on StackOverflow here.