Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: how to fetch previous insert timestamp

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?

like image 421
Alex Tokarev Avatar asked Dec 21 '25 23:12

Alex Tokarev


1 Answers

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();
like image 84
Sam Choukri Avatar answered Dec 24 '25 13:12

Sam Choukri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!