[Solved] MySql database optimization on inner join

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. 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.
Optimal indexes for this query:
ALTER TABLE `regular_challan_sales` ADD INDEX `regular_sales_idx_orderdateactual` (`OrderDateActual`);
ALTER TABLE `regular_challan_sales_details` ADD INDEX `regular_sales_idx_uniqueid` (`UniqueID`);
The optimized query:
SELECT
        DISTINCT rcs.ID,
        rcs.UniqueID,
        rcs.ReferanceNo,
        rcs.OrderDateActual,
        rcs.DelivaredToCus,
        rcs.PacketNumber,
        rcs.PackingCharge,
        rcs.TransportCharge,
        rcs.OtherAdjustment,
        (SELECT
            SUM(rcsd.TotalPrice) AS TotalPrice 
        FROM
            regular_challan_sales_details rcsd 
        WHERE
            rcsd.UniqueID = rcs.UniqueID LIMIT 1) AS TotalPrice 
    FROM
        regular_challan_sales rcs 
    WHERE
        rcs.OrderDateActual >= '2013-12-01' 
        AND rcs.OrderDateActual <= '2014-05-01' 
    ORDER BY
        rcs.OrderDateActual ASC

Related Articles



* original question posted on StackOverflow here.