[Solved] MySQL - JOIN to identify affect of updates on a single column

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 `building` ADD INDEX `building_idx_id` (`id`);
ALTER TABLE `building_floor` ADD INDEX `building_floor_idx_id` (`id`);
ALTER TABLE `department` ADD INDEX `department_idx_id` (`id`);
ALTER TABLE `security_clearance` ADD INDEX `security_clearance_idx_id` (`id`);
The optimized query:
SELECT
        employee.id,
        employee.name,
        employee.position,
        security_clearance.id,
        security_clearance.description,
        department.id,
        department.name,
        building.id,
        building.name,
        building_floor.id,
        building_floor.clearance_working_hours,
        building_floor.clearance_non_working_hours 
    FROM
        employee 
    LEFT JOIN
        department 
            ON employee.department = department.id 
    LEFT JOIN
        building_floor 
            ON department.id = building_floor.id 
    LEFT JOIN
        building 
            ON building_floor.building_id = building.id 
    LEFT JOIN
        security_clearance 
            ON employee.clearance_id = security_clearance.id 
            AND building_floor.clearance_working_hours = security_clearance.id 
            AND building_floor.clearance_non_working_hours = security_clearance.id

Related Articles



* original question posted on StackOverflow here.