I am reluctant to enter this code I came up with below:
UPDATE a_fees
SET active = 'N'
WHERE EXISTS
(
SELECT fee_id, (
audit_fees + audit_related_fees + tax_fees + other_fees
) AS total_fees
FROM a_fees
WHERE verified = 'N'
GROUP BY fee_id
HAVING total_fees < 5000);
Because I run this similar code (below) and I get all the results in the table returned, which makes me think this code above will update all the records in the table.
When I do the sub-select, it returns only the portion I am concerned with.
However, when I add the outermost selection statement, it returns the whole table.
SELECT fee_id
FROM a_fees
WHERE EXISTS (
SELECT fee_id, (
audit_fees + audit_related_fees + tax_fees + other_fees
) AS total_fees
FROM a_fees
WHERE verified = 'N'
GROUP BY fee_id
HAVING total_fees <5000;
Any advice how to set active=’N’ for records in the table where the sum of four columns is less than $5,000 would be great. Thanks in advance.
The EXISTS condition is considered to be met if the subquery returns at least one row.
So you’re right, the first UPDATE could update all the record of the table.
You should use IN clause instead of EXISTS, and there’s also no need to use a GROUP BY clause since fee_id is unique:
or you should put the condition in the subquery: