How do I automatically update a timestamp in PostgreSQL

后端 未结 4 571
执念已碎
执念已碎 2020-12-07 08:15

I want the code to be able to automatically update the time stamp when a new row is inserted as I can do in MySQL using CURRENT_TIMESTAMP.

How will I be able to achi

4条回答
  •  时光取名叫无心
    2020-12-07 08:54

    Updating timestamp, only if the values changed

    Based on E.J's link and add a if statement from this link (https://stackoverflow.com/a/3084254/1526023)

    CREATE OR REPLACE FUNCTION update_modified_column()
    RETURNS TRIGGER AS $$
    BEGIN
       IF row(NEW.*) IS DISTINCT FROM row(OLD.*) THEN
          NEW.modified = now(); 
          RETURN NEW;
       ELSE
          RETURN OLD;
       END IF;
    END;
    $$ language 'plpgsql';
    

提交回复
热议问题