0

I'm postgres newbie and i have a question regarding triggers. Lets say we have 2 tables. One with cities and one with people.

CITIES:

enter image description here

PEOPLE:

enter image description here

I need a trigger that updates 'processed' value in table cities from 0 to 1 when 'processed' value in table people updates from 0 to 1 for all people from that city.

For example: John, Ian and Claire are from Berlin and when 'processed' value is updated to 1 for each of them, then the trigger updates processed value for Berlin in table cities to 1.

What is the best way to do this?

1
  • 2
    This seems to be the wrong way to structure the data. Just use a join to look to see whether the city has been processed. Commented Jun 13, 2017 at 11:23

2 Answers 2

1

This will work:

CREATE OR REPLACE FUNCTION mytrigger() RETURNS TRIGGER AS $mytrigger$
    BEGIN
        IF (SELECT EXISTS (SELECT 1 FROM PEOPLE WHERE city_id = NEW.city_id AND processed = '0')) THEN
            UPDATE CITIES SET processed = '0' WHERE id = NEW.city_id;
            RETURN NEW;
        ELSE
            UPDATE CITIES SET processed = '1' WHERE id = NEW.city_id;
            RETURN NEW;
        END IF;
    END;
$mytrigger$ LANGUAGE plpgsql;

CREATE TRIGGER mytrigger
AFTER UPDATE ON PEOPLE
    FOR EACH ROW EXECUTE PROCEDURE mytrigger();
Sign up to request clarification or add additional context in comments.

Comments

1

try this query:

with c as (
    select city_id
    from people
    where name = NEW.name
)
, a as (
select avg(processed) 
from people
join c on c.city_id = people.city_id
)
update cities u
set processed = 1
from a
where u.id = a.city_id
and avg = 1

alias c gets city id, then a aggregates processed for that sict id in people and lastly update updates only when all names are processed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.