Postgresql Current timestamp on Update

后端 未结 3 1352
感动是毒
感动是毒 2020-12-13 07:30

What is the postgres equivalent of the below mysql code

CREATE TABLE t1 (
  created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  modified TIMESTAMP DEFAULT CURRENT         


        
相关标签:
3条回答
  • 2020-12-13 08:00

    Thank you for the information Mithun and Alex Brasetvik.

    I'd like to add one minor tweak to the trigger. Since we mostly likely want the modified column to store the timestamp when the row was last changed, not when it was the target of an UPDATE statement, we have to compare the new and the old value of the row. We update the modified column only if these two values differ.

    CREATE OR REPLACE FUNCTION update_modified_timestamp() RETURNS TRIGGER 
    LANGUAGE plpgsql
    AS
    $$
    BEGIN
        IF (NEW != OLD) THEN
            NEW.modified = CURRENT_TIMESTAMP;
            RETURN NEW;
        END IF;
        RETURN OLD;
    END;
    $$;
    

    This trigger ensures that the modified column is updated only if the UPDATE operation actually changes the values stored in the row.

    0 讨论(0)
  • 2020-12-13 08:00

    Update it with a trigger. Documentation and examples.

    0 讨论(0)
  • 2020-12-13 08:01

    Just make sure all tables have the same columnname:

    CREATE OR REPLACE FUNCTION upd_timestamp() RETURNS TRIGGER 
    LANGUAGE plpgsql
    AS
    $$
    BEGIN
        NEW.modified = CURRENT_TIMESTAMP;
        RETURN NEW;
    END;
    $$;
    
    CREATE TRIGGER t_name
      BEFORE UPDATE
      ON tablename
      FOR EACH ROW
      EXECUTE PROCEDURE upd_timestamp();
    
    0 讨论(0)
提交回复
热议问题