For the query above, the following recommendations will be helpful as part of the SQL tuning process.
You'll find 3 sections below:
The optimization process and recommendations:
- Avoid Calling Functions With Indexed Columns (query line: 16): 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 `attempt_date` is indexed, the index won’t be used as it’s wrapped with the function `DATE_SUB`. 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.
- Avoid Calling Functions With Indexed Columns (query line: 17): 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 `attempt_date` is indexed, the index won’t be used as it’s wrapped with the function `DATE_SUB`. 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.
- Avoid Calling Functions With Indexed Columns (query line: 18): 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 `attempt_date` is indexed, the index won’t be used as it’s wrapped with the function `DATE_SUB`. 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.
- 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 `er_login_attempts` ADD INDEX `er_attempts_idx_attempt_date` (`attempt_date`);
The optimized query:
SELECT
count(cinc.id) AS cinc_minuts,
count(deu.id) AS deu_minuts,
count(quinze.id) AS quinze_minuts
FROM
er_login_attempts cinc,
er_login_attempts deu,
er_login_attempts quinze
WHERE
'[email protected]' IN (
cinc.target_mail, deu.target_mail, quinze.target_mail
)
AND '1.11.11.111' IN (
cinc.ip_from, deu.ip_from, quinze.ip_from
)
AND cinc.attempt_date BETWEEN MAX(cinc.attempt_date) AND DATE_SUB(MAX(cinc.attempt_date), INTERVAL 5 minutes)
AND deu.attempt_date BETWEEN MAX(deu.attempt_date) AND DATE_SUB(MAX(deu.attempt_date), INTERVAL 10 minutes)
AND quinze.attempt_date BETWEEN MAX(quinze.attempt_date) AND DATE_SUB(MAX(quinze.attempt_date), INTERVAL 5 minutes)