Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between PostgreSQL now() and transaction_timestamp() functions?

In the official documentation, both functions have the same description:

Current date and time (start of current transaction)

Is there a difference between the two functions, and if not, why do both exist? Thanks.

like image 257
TheWildHealer Avatar asked Oct 16 '25 16:10

TheWildHealer


2 Answers

now and transaction_timestamp are equivalent to the SQL standard current_timestamp. All report the start time of the transaction.

In terms of transactions, there are two timestamps to think of. the start of the transaction & the time each individual statement is executed. Conceptually, there is also the end time of the transaction which one can get by running a select statement_timestamp() trx_end_timestamp at the very end, just before the commit / rollback.

If you run the following in psql [copy the whole line & paste into psql shell]

BEGIN; SELECT PG_SLEEP(5); SELECT NOW(), CURRENT_TIMESTAMP, TRANSACTION_TIMESTAMP(), STATEMENT_TIMESTAMP(); COMMIT;

I got this output:

              now              |       current_timestamp       |     transaction_timestamp     |      statement_timestamp
-------------------------------+-------------------------------+-------------------------------+-------------------------------
 2019-04-23 11:15:18.676855-04 | 2019-04-23 11:15:18.676855-04 | 2019-04-23 11:15:18.676855-04 | 2019-04-23 11:15:23.713275-04
(1 row)

You can see clearly that NOW, CURRENT_TIMESTAMP, TRANSACTION_TIMESTAMP are equivalent, and STATEMENT_TIMESTAMP has a 5 second offset because we slept for 5 seconds.

BTW, CURRENT_TIMESTAMP is in the sql standard. The others are postgresql specific, though other databases may also implement them

like image 119
Haleemur Ali Avatar answered Oct 19 '25 13:10

Haleemur Ali


The answer is in the doc your mention:

now() is a traditional PostgreSQL equivalent to transaction_timestamp().

So, they are the same, and they are here for historical / backward compatibility, and some could argue for the simplicity of the function name.

like image 30
JGH Avatar answered Oct 19 '25 11:10

JGH