[Solved] MySQL Query returns unexpected results

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: 28): 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 `f_location` is indexed, the index won’t be used as it’s wrapped with the function `concat`. 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: 29): 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 `log_status` is indexed, the index won’t be used as it’s wrapped with the function `concat`. 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.
  3. Avoid Subqueries (query line: 15): 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.
  4. 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:
SELECT
        fullname AS 'FullName',
        plannum AS 'Plan_Number',
        remarks AS 'Remarks',
        pre_type AS 'Pre_Need_Type',
        concat(x.id,
        '-PRENEED') AS 'Identification' 
    FROM
        preneed_tb AS x 
    LEFT JOIN
        filelocation 
            ON filelocation.f_id = x.id 
    LEFT JOIN
        (
            SELECT
                max(f_logs.id),
                f_logs.f_id,
                f_logs.log_status 
            FROM
                f_logs 
            GROUP BY
                f_logs.f_id 
            ORDER BY
                NULL
        ) AS y 
            ON y.f_id = x.id 
    WHERE
        concat(f_location, ' ') LIKE 'SFDSF %' 
        AND concat(y.log_status, ' ') LIKE 'IN STORA%'

Related Articles



* original question posted on StackOverflow here.