now() default values are all showing same timestamp

Ryan Fisch picture Ryan Fisch · Aug 31, 2012 · Viewed 35.1k times · Source

I have created my tables with a column (type: timestamp with timezone) and set its default value to now() (current_timestamp()).

I run a series of inserts in separate statements in a single function and I noticed all the timestamps are equal down to the (ms), is the function value somehow cached and shared for the entire function call or transaction?

Answer

a_horse_with_no_name picture a_horse_with_no_name · Aug 31, 2012

That is expected and documented behaviour:

From the manual:

Since these functions return the start time of the current transaction, their values do not change during the transaction. This is considered a feature: the intent is to allow a single transaction to have a consistent notion of the "current" time, so that multiple modifications within the same transaction bear the same time stamp.

If you want something that changes each time you run a statement, you need to use statement_timestamp() or even clock_timestamp() (again see the description in the manual)