PostgreSQL now()和transaction_timestamp()函数之间有区别吗?

时间:2019-04-23 15:04:07

标签: postgresql datetime

the official documentation中,两个函数具有相同的描述:

  

当前日期和时间(当前交易的开始)

两个功能之间是否有区别,如果没有,为什么两者都存在?谢谢。

2 个答案:

答案 0 :(得分:1)

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.

答案 1 :(得分:1)

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