[Solved] How did we get condition filtering value of 5 percent in this plan instead of 10 percent? MySQL 8.0

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.
  2. Prefer IN Clause Over OR Conditions (modified query below): Using an IN clause is far more efficient than OR conditions, when comparing a column to more than one optional values. When using an IN clause, the database sorts the list of values and uses a quick binary search.
Optimal indexes for this query:
ALTER TABLE `department` ADD INDEX `department_idx_dept_no` (`dept_no`);
ALTER TABLE `emp_address_phone` ADD INDEX `emp_phone_idx_emp_no_country` (`emp_no`,`country`);
ALTER TABLE `emp_dept` ADD INDEX `emp_dept_idx_emp_no` (`emp_no`);
ALTER TABLE `emp_salary` ADD INDEX `emp_salary_idx_emp_no_pf` (`emp_no`,`pf`);
ALTER TABLE `emp_title` ADD INDEX `emp_title_idx_emp_no` (`emp_no`);
ALTER TABLE `employee` ADD INDEX `employee_idx_hire_date` (`hire_date`);
ALTER TABLE `title` ADD INDEX `title_idx_title_no_title_created` (`title_no`,`title_created`);
The optimized query:
SELECT
        e.emp_no,
        concat(e.first_name,
        ' ',
        e.last_name),
        d.dept_name,
        t.title_name,
        es.salary,
        es.insurance,
        es.pf,
        ea.city,
        ea.state,
        ea.phone 
    FROM
        employee e 
    JOIN
        emp_salary es 
            ON e.emp_no = es.emp_no 
    JOIN
        emp_title et 
            ON et.emp_no = e.emp_no 
    JOIN
        title t 
            ON t.title_no = et.title_no 
    JOIN
        emp_address_phone ea 
            ON ea.emp_no = e.emp_no 
    JOIN
        emp_dept ed 
            ON e.emp_no = ed.emp_no 
    JOIN
        department d 
            ON d.dept_no = ed.dept_no 
    WHERE
        (
            e.hire_date > '2004-01-01' 
            OR e.hire_date < '1980-01-01'
        ) 
        AND (
            es.pf > 4.25 
            OR es.pf < 1.4
        ) 
        AND (
            t.title_created > '2006-01-01'
        ) 
        AND (
            ea.country IN (
                'Spain', 'Samoa', 'India'
            )
        )

Related Articles



* original question posted on StackOverflow here.