How can I get most recent time in a Postgres transaction

The question:

I noticed that Postgres caches the value of NOW() inside a transaction, e.g.:

lev=# BEGIN;
BEGIN
lev=# SELECT now();
              now
-------------------------------
 2022-04-07 19:16:52.358923-07
(1 row)

lev=# SELECTpg_sleep(1);
 pg_sleep
----------

(1 row)

lev=# SELECT now();
              now
-------------------------------
 2022-04-07 19:16:52.358923-07
(1 row)

Is there a way to get up-to-date time inside a transaction for every call to NOW()?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

As documented in the manual, now() (and the standard compliant current_timestamp) returns the time at the start of the transaction (and is an alias for transaction_timestamp())

If you want something that is independent of the statement or transaction start, use clock_timestamp()


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment