Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trigger keeps updating value in every row instead of particular one

I am trying to calculate a sum for each particular order. I am using this trigger but it doesn’t work properly, it updates every row with the same value instead of the only one with proper id.

done_services table

id
service_id
price

service table

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

id
name

payment table

id
sum
service_id
CREATE FUNCTION make_sum() RETURNS TRIGGER
    AS $$
        BEGIN
            UPDATE payment
                SET sum = (select sum(price) from done_services where service_id = new.service_id);
            RETURN NULL;
    END;$$ LANGUAGE plpgsql;
    
CREATE TRIGGER make_sum
AFTER INSERT ON basket FOR EACH ROW EXECUTE FUNCTION make_sum(); 

I used this command to enter an item
insert into done_services(id, service_id, price) values(uuid_generate_v4(), '76594d2f-7153-495f-9671-0ddaa331568c', 100);

But the sum changed for both rows instead of the only one with service id
Image

>Solution :

just missing something in your UPDATE statement :

UPDATE payment
   SET sum = (select sum(price) from done_services where service_id = new.service_id)
 WHERE service_id = new.service_id ;

Next time please create a dbfiddle with your data model, sample of data and queries.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading