[Solved] sql query taking huge time to execute mysql

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. Use Numeric Column Types For Numeric Values (query line: 26): Referencing a numeric value (e.g. 31) 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 `ledger_master` ADD INDEX `ledger_master_idx_company_code_ledger_code` (`company_code`,`ledger_code`);
ALTER TABLE `transaction_ledger` ADD INDEX `transaction_ledger_idx_ledger_cod_company_co_trans_date` (`ledger_code`,`company_code`,`trans_date`);
The optimized query:
SELECT
        b.ledger_name,
        a.trans_id,
        a.voucher_id,
        a.r_trans_id,
        a.voucher_number,
        date_format(a.trans_date,
        '%d-%m-%Y') AS trans_date,
        a.trans_type AS voucher_type,
        a.trans_type_name,
        CASE 
            WHEN Sum(a.trans_amount) > 0 THEN round(abs(Sum(a.trans_amount)),
            2) 
            ELSE 0 END AS amount_cr,
CASE 
    WHEN Sum(a.trans_amount) < 0 THEN round(abs(Sum(a.trans_amount)),
    2) 
    ELSE 0 END AS amount_dr 
FROM
transaction_ledger AS a 
LEFT JOIN
ledger_master AS b 
    ON b.company_code = a.company_code 
    AND b.ledger_code = a.ledger_ref_code 
WHERE
a.ledger_code = '31' 
AND a.company_code = '65370928-9ee1-40f6-ac38-e7a381908fd9' 
AND a.trans_date BETWEEN '2010-04-01' AND '2014-01-31' 
AND a.trans_type_name IN (
    'Sales', 'Purchase', 'Receipt', 'Payment', 'Journal', 'Credit Note', 'Debit Note', 'Contra'
) 
GROUP BY
b.ledger_name,
a.trans_id,
a.voucher_id,
a.r_trans_id,
a.voucher_number,
a.trans_date,
a.company_code,
a.narration,
a.trans_type,
a.trans_type_name 
ORDER BY
date_format(a.trans_date,
'%Y-%m-%d'),
a.voucher_number

Related Articles



* original question posted on StackOverflow here.