I have the table Photographies with the columns: Name, Author, Date, Updated date.
I would like to set Update date as default current_date when a new record is inserted or when a record is updated.
How should I proceed with this?
Advertisement
Answer
Welcome to SO. Take a look at triggers
.
Basically you only need to create a function to perform the updated ..
CREATE OR REPLACE FUNCTION update_date() RETURNS trigger AS $BODY$ BEGIN NEW.updated = current_date; RETURN NEW; END; $BODY$ LANGUAGE 'plpgsql';
.. and attach it to a BEFORE INSERT OR UPDATE
trigger like this
CREATE TRIGGER check_update BEFORE INSERT OR UPDATE ON photographies FOR EACH ROW EXECUTE PROCEDURE update_date();
After inserting a record ..
INSERT INTO photographies (name, author, date) VALUES ('José Saramago ','As Intermitências da Morte','2005-01-01');
.. you have your updated column with the current date
SELECT * FROM photographies ; name | author | date | updated ----------------+----------------------------+------------+------------ José Saramago | As Intermitências da Morte | 2005-01-01 | 2019-12-06 (1 Zeile)