[Solved] Eliminate a user who meets the condition, even though they may not meet the condition in other rows

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 Calling Functions With Indexed Columns (query line: 25): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. For example, if the column `shift_start` is indexed, the index won’t be used as it’s wrapped with the function `date`. If you can’t find an alternative condition that won’t use a function call, a possible solution is to store the required value in a new indexed column.
  2. Avoid Calling Functions With Indexed Columns (query line: 26): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. For example, if the column `shift_start` is indexed, the index won’t be used as it’s wrapped with the function `date`. If you can’t find an alternative condition that won’t use a function call, a possible solution is to store the required value in a new indexed column.
The optimized query:
SELECT
        secud_id,
        secud_fname,
        secud_sname,
        users.user_id,
        users.user_owner,
        users.user_level,
        shifts.shift_start,
        GROUP_CONCAT(DISTINCT uq_name SEPARATOR ' ') quals 
    FROM
        user_data 
    INNER JOIN
        users 
            ON user_data.secud_ulink = users.user_id 
    LEFT JOIN
        user_quals 
            ON users.user_id = user_quals.uq_user 
    LEFT JOIN
        shifts 
            ON shifts.shift_user = users.user_id 
    WHERE
        users.user_owner = 2 
        AND users.user_level = 'Personnel' 
        AND (
            date(shifts.shift_start) <> '2016-03-16' 
            OR date(shifts.shift_start) IS NULL
        ) 
        AND users.user_active = 1 
    GROUP BY
        users.user_id 
    ORDER BY
        secud_sname ASC

Related Articles



* original question posted on StackOverflow here.