Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

now() default values are all showing same timestamp

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?

like image 796
Ryan Fisch Avatar asked Aug 31 '12 13:08

Ryan Fisch


People also ask

What is the default value of timestamp?

TIMESTAMP Initialization and the NULL AttributeDEFAULT NULL can be used to explicitly specify NULL as the default value. (For a TIMESTAMP column not declared with the NULL attribute, DEFAULT NULL is invalid.) If a TIMESTAMP column permits NULL values, assigning NULL sets it to NULL , not to the current timestamp.

What is the default value for DATETIME in MySQL?

In MySQL, you cannot use a function or an expression as the default value for any type of column, except for the TIMESTAMP data type column, for which you can specify the CURRENT_TIMESTAMP as the default.

What is the current_ timestamp ON UPDATE current_ timestamp?

The CURRENT_TIMESTAMP() function returns the current date and time. Note: The date and time is returned as "YYYY-MM-DD HH-MM-SS" (string) or as YYYYMMDDHHMMSS.

How do I add a default value to a timestamp column?

Use of DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP is specific to TIMESTAMP. The DEFAULT clause also can be used to specify a constant (nonautomatic) default value; for example, DEFAULT 0 or DEFAULT '2000-01-01 00:00:00'.


2 Answers

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)

like image 62
a_horse_with_no_name Avatar answered Oct 15 '22 23:10

a_horse_with_no_name


now() and current_timestamp are STABLE functions returning the point in time when the transaction started as timestamptz.

Consider one of the other options PostgreSQL offers, in particular statement_timestamp(). The manual:

statement_timestamp() returns the start time of the current statement (more specifically, the time of receipt of the latest command message from the client)

like image 45
Erwin Brandstetter Avatar answered Oct 15 '22 22:10

Erwin Brandstetter