4

I have a small table for news. I want to make a trigger which sets the update date and update time in the row (only for the rows that were updated)

I tried making the following:

CREATE FUNCTION add_update_dates()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
  IF (OLD.news_name IS DISTINCT FROM NEW.news_name OR
  OLD.news_description IS DISTINCT FROM NEW.news_description OR
  OLD.news_text IS DISTINCT FROM NEW.news_text) THEN
  UPDATE news SET news_update_date = current_date, news_update_time = current_time;
END IF;
RETURN new;
END
$$;

CREATE TRIGGER update_news_dates
AFTER UPDATE ON news
FOR EACH ROW
EXECUTE PROCEDURE add_update_dates();

But the trigger updates each row in my table (even those that are not updated), when I want only the updated ones. What am I doing wrong?

2
  • Is the update table statement on same table, inside the trigger, allowed in Postgresql?. I mean, In oracle, we would have received a mutating table error. Commented Dec 11, 2017 at 18:02
  • @KaushikNayak: I think it's allowed in an AFTER UPDATE trigger, but not in a BEFORE UPDATE trigger Commented Dec 11, 2017 at 21:29

1 Answer 1

9

Your update statement is updating all the rows in the table! It has no where clause.

Just use assignment:

CREATE FUNCTION add_update_dates()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
  IF (OLD.news_name IS DISTINCT FROM NEW.news_name OR
      OLD.news_description IS DISTINCT FROM NEW.news_description OR
      OLD.news_text IS DISTINCT FROM NEW.news_text
     ) THEN
    NEW.news_update_date := current_date;
    NEW.news_update_time := current_time;
  END IF;
  RETURN new;
END;
$$;

As an aside, storing date/time in separate columns makes no sense to me.

Sign up to request clarification or add additional context in comments.

1 Comment

You'll also need to change the trigger definition to BEFORE UPDATE

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.