[Solved] SQL query need to get user where program column includes certain program

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. 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'.
  2. Replace Join With Exists To Avoid Redundant Grouping (modified query below): When a joined table isn’t used anywhere other than in the WHERE clause, it's equivalent to an EXISTS subquery, which often performs better. In cases where the DISTINCT or GROUP BY clause contains only columns from the Primary key, they can be removed to further improve performance, as after this transformation, they are redundant.
  3. Use Numeric Column Types For Numeric Values (query line: 25): Referencing a numeric value (e.g. 1) 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.
The optimized query:
SELECT
        WPP.USERID 
    FROM
        WEBPROGRAMPARTICIPANTS WPP 
    WHERE
        (
            CONFIRMED = 1 
            AND 1 = 1 
            AND 1 = 1 
            AND WPP.PROGRAMCODE = 'CL2010'
        ) 
        AND (
            EXISTS (
                SELECT
                    1 
                FROM
                    WEBPROGRAMS WP 
                WHERE
                    (
                        (
                            WPP.PROGRAMCODE = WP.PROGRAMCODE
                        ) 
                        AND (
                            WP.PROGRAMTYPE IN (
                                '1'
                            )
                        )
                    ) 
                    AND (
                        WP.PROGRAMSTARTDATE >= '2000-01-01'
                    )
            )
        ) 
    GROUP BY
        WPP.USERID 
    HAVING
        COUNT(WPP.PROGRAMCODE) > 1 
    ORDER BY
        NULL

Related Articles



* original question posted on StackOverflow here.