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 Subqueries (query line: 21): 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.
- 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.
- Replace Left Join With Subquery (modified query below): The pattern of inflating the amount of data (using joins) and deflating (using GROUP BY) usually slows down queries. In this case, it can be avoided by moving some of the logic to the SELECT clause, and therefore removing some of the LEFT JOINs. In some cases, this transformation can lead to an obsolete GROUP BY clause, which can also be removed.
- Use Numeric Column Types For Numeric Values (query line: 37): Referencing a numeric value (e.g. 3) as a string in a WHERE clause might result in poor performance. Possible impacts of storing numbers as varchars: more space will be used, you won't be able to perform arithmetic operations, the data won't be self-validated, aggregation functions like SUM won't work, the output may sort incorrectly and more. If the column is numeric, remove the quotes from the constant value, to make sure a numeric comparison is done.
Optimal indexes for this query:
ALTER TABLE `clientdetails` ADD INDEX `clientdetails_idx_id` (`id`);
ALTER TABLE `customer` ADD INDEX `customer_idx_switchedoff_companyid` (`switchedoff`,`companyid`);
ALTER TABLE `members` ADD INDEX `members_idx_id` (`id`);
ALTER TABLE `updates` ADD INDEX `updates_idx_date` (`date`);
The optimized query:
members.fullname AS acc_manager,
ON clientdetails.id = customer.id
ON members.id = customer.consultant_name
Max(updates.`date`) AS MaxDate,
members.id = updates.consultant LIMIT 1) AS fullname
updates.date DESC) u
ON customer.id = u.clientid
customer.switchedoff = 'N'
AND customer.companyid <> '3'