3

Suppose that I have table

create table foo (
 insert_current timestamp default now(),
 insert_previous timestamp,
 bar int primary key,
 baz varchar(10)
);

The data will be replaced now and then when fresh batch arrived. I would like to keep track on when previous batch was inserted as well as current timestamp. What would be a good way to do this?

asked May 24, 2012 at 4:34

2 Answers 2

3

I would create a trigger that automatically sets insert_current and insert_previous on UPDATE statements.

First, create the trigger function:

CREATE OR REPLACE FUNCTION do_update() RETURNS "trigger"
AS $$
BEGIN
 NEW.insert_previous := OLD.insert_current;
 NEW.insert_current := NOW();
 return NEW;
END;
$$
LANGUAGE plpgsql;

Then add the trigger to your table:

CREATE TRIGGER do_update
BEFORE UPDATE ON foo
FOR EACH ROW
EXECUTE PROCEDURE do_update();
answered May 24, 2012 at 7:04
Sign up to request clarification or add additional context in comments.

Comments

3

When you update a row, copy the value of insert_current to insert_previous and set insert_current to the current timestamp:

UPDATE foo
 SET baz = 'whatever',
 insert_previous = insert_current,
 insert_current = NOW()
 WHERE bar = 1;
answered May 24, 2012 at 4:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.