0

I have a table like this

-----------------------------------------------------------------------------------
id                                    | notification_sent | times_notification_sent
-----------------------------------------------------------------------------------
4a1717a2-6e1e-4af6-aa34-8262899aa060  | t                 | 0

Here notification sent is boolean field and times_notification_sent is int. I am trying to create trigger which will increment the times_notification_sent by 1 when notification_sent is changed from true to false.

I am using following function and triggers but it not working.

CREATE OR REPLACE FUNCTION update_sent_counter_for_watch()  RETURNS TRIGGER 
LANGUAGE plpgsql
AS $$ BEGIN
IF OLD.notification_sent IS TRUE AND NEW.notification_sent IS FALSE THEN
   UPDATE "watch" SET "times_notification_sent" = "times_notification_sent" + 1 WHERE "id" = OLD."id";
END IF;
END;
$$;

CREATE TRIGGER "update_times_sent_counter" AFTER UPDATE OF "times_notification_sent" ON "public"."watch"
FOR EACH ROW
WHEN (OLD.notification_sent IS DISTINCT FROM NEW.notification_sent)
EXECUTE PROCEDURE "public"."update_sent_counter_for_watch"();

1 Answer 1

1

You have two errors:

You don't need an update, just assign the new value:

CREATE OR REPLACE FUNCTION update_sent_counter_for_watch()  
  RETURNS TRIGGER 
  LANGUAGE plpgsql
AS 
$$ 
BEGIN
  IF OLD.notification_sent IS TRUE AND NEW.notification_sent IS FALSE THEN
    new.times_notification_sent := old.times_notification_sent + 1;
  END IF;
  RETURN new;
END;
$$;

And you can't change the value in an after update triger, you need to change it to a before trigger:

CREATE TRIGGER "update_times_sent_counter" BEFORE UPDATE OF "times_notification_sent" 
  ON "public"."watch"
  FOR EACH ROW
WHEN (OLD.notification_sent IS DISTINCT FROM NEW.notification_sent)
EXECUTE PROCEDURE "public"."update_sent_counter_for_watch"();
Sign up to request clarification or add additional context in comments.

1 Comment

Both of you were correct. Thank you very much for your help.

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.