[Solved] Optimizing the SQL Query for Calculating account balance

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. Avoid Correlated Subqueries (query line: 15): A correlated subquery is a subquery that contains a reference (column: accno) to a table that also appears in the outer query. Usually correlated queries can be rewritten with a join clause, which is the best practice. The database optimizer handles joins much better than correlated subqueries. Therefore, rephrasing the query with a join will allow the optimizer to use the most efficient execution plan for the query.
  2. 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.
  3. Explicitly ORDER BY After GROUP BY (modified query below): By default, the database sorts all 'GROUP BY col1, col2, ...' queries as if you specified 'ORDER BY col1, col2, ...' in the query as well. If a query includes a GROUP BY clause but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying 'ORDER BY NULL'.
  4. Replace Join With Exists To Avoid Redundant Grouping (modified query below): When a joined table isn’t used anywhere other than in the WHERE clause, it's equivalent to an EXISTS subquery, which often performs better. In cases where the DISTINCT or GROUP BY clause contains only columns from the Primary key, they can be removed to further improve performance, as after this transformation, they are redundant.
Optimal indexes for this query:
ALTER TABLE `Bankdetails` ADD INDEX `bankdetails_idx_accno_accname_opbal` (`accno`,`accname`,`opbal`);
ALTER TABLE `Trandetails` ADD INDEX `trandetails_idx_trantype_accno` (`Trantype`,`accno`);
ALTER TABLE `Trandetails` ADD INDEX `trandetails_idx_accno` (`AccNo`);
The optimized query:
SELECT
        bd.accname,
        bd.accno,
        (bd.opbal - isnull((SELECT
            SUM(Trandetails.Amount) 
        FROM
            Trandetails 
        WHERE
            Trandetails.Trantype = 'Debit' 
            AND Trandetails.accno = bd.accno 
        GROUP BY
            Trandetails.accno 
        ORDER BY
            NULL),
        0) + isnull((SELECT
            SUM(Trandetails.Amount) 
        FROM
            Trandetails 
        WHERE
            Trandetails.Trantype = 'Credit' 
            AND Trandetails.accno = bd.accno 
        GROUP BY
            Trandetails.accno 
        ORDER BY
            NULL),
        0)) AS Bal 
    FROM
        Bankdetails BD 
    WHERE
        (
            EXISTS (
                SELECT
                    1 
                FROM
                    Trandetails TD 
                WHERE
                    td.AccNo = bd.AccNo
            )
        ) 
    GROUP BY
        bd.accno,
        bd.accname,
        bd.opbal 
    ORDER BY
        NULL

Related Articles



* original question posted on StackOverflow here.