Search code examples
sqldelphidelphi-2009advantage-database-serversql-optimization

SQL optimization on the following 7 update queries. same table. Combine into one?


The following queries update the same table like 7 times.. I would appreciate your help on how I might optimize this by putting it into one query so it passes through the table only once instead of 7 times.. This is really slowing down performance on large datasets..

Thanks.

P.S. I don't know if it will still work out but each query string depends on the query before it to accurately calculate.. So if we need to keep them separate in order to keep it accurate then I could use some help optimizing each string (query) individually.

The following SQL queries are made in Delphi 2009 So the format may be a little different but you should still be able to read the query pretty easily..

Str1 :=
'update user set amount = ' +
  '(select round(sum(bill.amount),2) from bill where ' +
  'bill.user = user.code); ' +
'update user set pay = ' +
  '(select round(sum(bill.pay),2) from bill where ' +
  'bill.user = user.code); ' +
'update user set balance = round(amount + pay,2);';

//execute query

 Str1 :=
'update user set group_amt = ' +
  '(select sum(bill.amount) from bill where ' +
  'bill.client = user.client); ' +
'update user set group_pay = ' +
  '(select sum(bill.pay) from bill where ' +
  'bill.client = user.client); ' +
'update user set group_bal = round(group_amt + group_pay,2);';

 //execute query

Str1 :=
'update user set bal_flag = true ' +
'where abs(balance) > 0.001 and bal_flag = false;';

Solution

  • I suspect you can merge 6 of the updates into just 2 updates...

    UPDATE
      user
    SET
      amount   = bill.amount,
      pay      = bill.pay,
      balance  = bill.pay + bill.amount
    FROM
    (
      SELECT
        user,
        round(sum(bill.amount),2)   AS amount,
        round(sum(bill.pay)   ,2)   AS pay
      FROM
        bill
      GROUP BY
        user
    )
      AS bill
    WHERE
      bill.user = user.code
    

    And nearly identically...

    UPDATE
      user
    SET
      group_amt = bill.amount,
      group_pay = bill.pay,
      group_bal = bill.pay + bill.amount
    FROM
    (
      SELECT
        client,
        round(sum(bill.amount),2)   AS amount,
        round(sum(bill.pay)   ,2)   AS pay
      FROM
        bill
      GROUP BY
        client
    )
      AS bill
    WHERE
      bill.client = user.client