This seems to be taking a very long time on large data sets. Will combining the first and last 3 queries into 1 make it faster? Does anyone have any input on what might make it faster? I appreciate it.
update "detail" set bal = (units * amount) where code_type = 'AB';
update "detail" set bal = (units * amount) where code_type = 'CD';
update "detail" set bal = (units * amount) where code_type = 'EF';
update "detail" set bal = (units * amount * -1) where code_type = 'GH';
update "detail" set bal = (units * amount * -1) where code_type = 'IK';
update "detail" set bal = (units * amount * -1) where code_type = 'LM';
update "detail" set bal = 0 where code_type = 'NO';
Additionally –
update bill set pay =
(select round(sum(bd1.bal),2) from "detail" bd1 where
bd1.inv = bill.inv and
(bd1.code_type = 'AB' or bd1.code_type = 'CD'));
update bill set pay = 0 where pay is null;
update bill set cost =
(select round(sum(bd2.bal),2) from "detail" bd2 where
bd2.inv = bill.inv and
(not (bd2.code_type = 'AB' or bd2.code_type = 'CD')));
update bill set cost = 0 where cost is null;
update bill set balance = round(cost + pay,2);
Thanks
Performance probably stinks because you are updating the entire table, and you are updating it twelve times. If the table is seriously big, that’s going to take
time. Also, those two embedded subqueries will each get run once per row. Ouch.
The following frankenquery rolls everything into a single statement. It still has to hit the entire table, but at least it only does it once. I can’t check syntax
or test it against data, but this or something very much like it should work.
EDITED, split this into two updates (thus, two table scans requried)
and
Moral: the
CASEstatement can be the SQL developer’s best friend.