In PostgreSQL, the now()
function returns the current date and time (including the time zone offset), at the start of the current transaction.
It’s the equivalent of the transaction_timestamp()
function.
It’s also similar to the current_timestamp
function (when called without an argument).
The now()
function doesn’t accept any parameters, so you can’t specify its precision, whereas current_timestamp
can be called with or without a precision parameter.
Also, now()
is non-SQL-standard (as is the transaction_timestamp()
function).
Syntax
The syntax goes like this:
now()
No arguments are required or accepted.
Basic Example
Here’s a basic example to demonstrate.
SELECT now();
Result:
2020-07-02 09:51:12.088506+10
Within a Transaction
Here’s an example to demonstrate how it works within a transaction.
BEGIN;
SELECT now();
SELECT pg_sleep(5);
SELECT now();
SELECT pg_sleep(5);
SELECT now();
COMMIT;
Here’s the full output within my terminal when using psql:
postgres=# BEGIN; BEGIN postgres=# SELECT now(); now ------------------------------- 2020-07-02 09:51:53.905091+10 (1 row) postgres=# SELECT pg_sleep(5); pg_sleep ---------- (1 row) postgres=# SELECT now(); now ------------------------------- 2020-07-02 09:51:53.905091+10 (1 row) postgres=# SELECT pg_sleep(5); pg_sleep ---------- (1 row) postgres=# SELECT now(); now ------------------------------- 2020-07-02 09:51:53.905091+10 (1 row) postgres=# COMMIT; COMMIT
All three time values are identical, even though the pg_sleep()
function was used to delay execution between each call to now()
, each of which happened to be in its own SQL statement.
So we can see that the time returned for each statement is based on the start time of the current transaction – not the statement. It doesn’t change as the transaction progresses.
This allows 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.
Multiple Calls within a Statement
It also doesn’t change as the statement progresses.
\x
SELECT
now(),
pg_sleep(5),
now(),
pg_sleep(5),
now();
Result (using vertical output):
now | 2020-07-02 09:53:33.766806+10 pg_sleep | now | 2020-07-02 09:53:33.766806+10 pg_sleep | now | 2020-07-02 09:53:33.766806+10
Again, all three time values are identical, even though the pg_sleep()
function was used to delay execution between each call to now()
.
This is in contrast to statement_timestamp()
, which does change with each statement, and also the clock_timestamp()
function, which changes even as it progresses through each statement (if called multiple times within the statement).