[Solved] slow mysql query, set indexes or optimise

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. 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.
Optimal indexes for this query:
ALTER TABLE `newer` ADD INDEX `newer_idx_thoroughfare_building_name` (`THOROUGHFARE`,`BUILDING_NAME`);
ALTER TABLE `upcdata` ADD INDEX `upcdata_idx_building_name` (`Building Name`);
The optimized query:
SELECT
        t1.`Geo ID`,
        t1.`Sub Unit Geo ID`,
        t1.`Sub Unit SW ID`,
        t1.`Building No`,
        t1.`Building Name`,
        t1.Road,
        t2.ID `Matching NEW_ID`,
        t2.Sub,
        t2.SUB_BUILDING_NAME,
        t2.BUILDING_NAME,
        t2.BUILDING_NUMBER,
        t2.THOROUGHFARE,
        t2.E - t1.Easting `East Difference`,
        t2.N - t1.Northing `North Difference` 
    FROM
        upcdata t1 
    JOIN
        newer t2 
            ON (
                t2.E * 1000
            ) BETWEEN t1.Easting - 25000 AND t1.Easting + 25000 
            AND (
                t2.N * 1000
            ) BETWEEN t1.Northing - 25000 AND t1.Northing + 25000 
            AND t1.Road = t2.THOROUGHFARE 
            AND t1.`Building Name` = t2.BUILDING_NAME 
            AND t1.`Building Name` <> '' 
    ORDER BY
        t1.`Geo ID`

Related Articles



* original question posted on StackOverflow here.