Professional Documents
Culture Documents
Update The Timestamp Column With The Use of TRIGGER
Update The Timestamp Column With The Use of TRIGGER
Facebookgoogle_plusTwitterLinkedInPinterestRedd
itPocketShare
Like MySQL, PostgreSQL doesn’t have different column for Datetime and Timestamp.
You can visit this MySQL article here:
In this post, I am sharing small demonstration on how to update a timestamp column
automatically when a row is updated in the table of the PostgreSQL.
In the big transactional system like the banking system, we always require last updated
datetime of every transaction and row.
But we can also create Trigger to perform this operation, and this automatic approach is
good.
Below is a small demonstration by creating update Trigger:
Create a sample table:
1 CREATE TABLE tbl_EmployeeDetails
2(
3 EmpID SERIAL
4 ,EmpName CHARACTER VARYING(50)
5 ,EmpDOB TIMESTAMP WITHOUT TIME ZONE
6 ,LastUpdatedDateTime TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW()
7 ,CONSTRAINT pk_tbl_EmployeeDetails_EmpID PRIMARY KEY(EmpID)
8 );
Insert a sample data for EmpName and EmpDOB column:
1 INSERT INTO tbl_EmployeeDetails
2 (EmpName,EmpDOB)
3 VALUES
4 ('Anvesh','1988-01-26')
5 ,('Neevan','2000-06-29')
6 ,('Martin','1985-08-04')
7 ,('Jeny','1990-09-12');
Create a Trigger function:
1 CREATE OR REPLACE FUNCTION trg_fn_tbl_EmployeeDetails_LastUpdatedDateTime()
2 RETURNS TRIGGER AS $$
3 BEGIN
4 NEW.LastUpdatedDateTime = NOW();
5 RETURN NEW;
6 END;
7 $$ language 'plpgsql';
Create an UPDATE TRIGGER:
1 CREATE TRIGGER trg_update_tbl_EmployeeDetails BEFORE UPDATE
2 ON tbl_EmployeeDetails FOR EACH ROW EXECUTE PROCEDURE
3 trg_fn_tbl_EmployeeDetails_LastUpdatedDateTime();
Update a record and check LastUpdatedDateTime:
1 UPDATE tbl_EmployeeDetails SET EmpDOB = '1991-09-12' WHERE EmpID=4;
The Result:
1 SELECT *FROM tbl_EmployeeDetails;