1

I have a table named vehicle like this

CREATE TABLE vehicle
(
    id                  varchar,
    status              TEXT,
    created_at          TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at          TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
   PRIMARY KEY (id)
   
);

I want to create a trigger which will on trigger only when the status value is modified.

till now have a trigger which work on whole table fields and it is written like this

first function

CREATE OR REPLACE FUNCTION public.update_timestamp()
    RETURNS trigger
    LANGUAGE plpgsql
AS
$function$
BEGIN
    NEW.status_updated_at = CURRENT_TIMESTAMP;
RETURN NEW;
END;
$function$
;

then trigger

create trigger update_timestamp
    before update
    on vehicle
    for each row
execute procedure update_timestamp();
 

reference for this trigger is this https://x-team.com/blog/automatic-timestamps-with-postgresql/

1
  • @LaurenzAlbe both cases . status change in any combination Commented May 26, 2021 at 7:51

1 Answer 1

2

you can change your trigger to execute trigger function only when status has changed:

create trigger update_timestamp
    before update
    on vehicle
    for each row
    when (OLD.status IS DISTINCT FROM NEW.status)
execute procedure update_timestamp();
Sign up to request clarification or add additional context in comments.

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.