Postgresql Current timestamp on Update

后端 未结 3 1369
感动是毒
感动是毒 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.

提交回复
热议问题