Question

I'm working on my first ever Trigger. When I'm doing an INSERT on table I want to conditionaly remove rows from other table.

Here is a trigger:

CREATE OR REPLACE FUNCTION clear_seen_by()
  RETURNS trigger AS
$BODY$
    BEGIN
         IF (OLD.popup = '1') THEN
              DELETE FROM news_seen_by;
            END IF;

        RETURN NULL;
    END;
   $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

Invoked by:

  CREATE TRIGGER clear_seen_by
  AFTER INSERT
  ON news
  FOR EACH STATEMENT
  EXECUTE PROCEDURE clear_seen_by();

As an error I see that NEW or OLD (if I motify the trigger) is not declared/unknown. Where is the problem?

Was it helpful?

Solution

In an INSERT statement you do not have an OLD record defined.

You should use NEW.popup instead, and also declare the trigger to be FOR EACH ROW.

  CREATE OR REPLACE FUNCTION clear_seen_by() RETURNS trigger AS
  $BODY$
    BEGIN
      IF (NEW.popup = '1') THEN
        DELETE FROM news_seen_by;
      END IF;

      RETURN NULL;
    END;
  $BODY$
  LANGUAGE plpgsql VOLATILE COST 100;


  CREATE TRIGGER
    clear_seen_by
  AFTER INSERT ON
    news
  FOR EACH ROW EXECUTE PROCEDURE
    clear_seen_by();

OTHER TIPS

You declare a trigger FOR EACH STATEMENT. Maybe you need FOR EACH ROW?

FOR EACH STATEMENT triggers do not have NEW and OLD.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top