How statement_timestamp() Works in PostgreSQL

In PostgreSQL, the statement_timestamp() function returns the current date and time (including the time zone offset), at the start of the current statement.

The function doesn’t accept any parameters, so you can’t specify its precision.

Also, statement_timestamp() is a non-SQL-standard function.

Syntax

The syntax goes like this:

statement_timestamp()

No arguments are required or accepted.

Basic Example

Here’s a basic example to demonstrate.

SELECT statement_timestamp();

Result:

2020-07-02 09:30:45.46903+10

Within a Transaction

Here’s an example to demonstrate how it works within a transaction.

BEGIN;
SELECT statement_timestamp();
SELECT pg_sleep(5);
SELECT statement_timestamp();
SELECT pg_sleep(5);
SELECT statement_timestamp();
COMMIT;

Here’s the full output within my terminal when using psql:

postgres=# BEGIN;
BEGIN
postgres=# SELECT statement_timestamp();
      statement_timestamp      
-------------------------------
 2020-07-02 09:31:13.363128+10
(1 row)


postgres=# SELECT pg_sleep(5);
 pg_sleep 
----------
 
(1 row)


postgres=# SELECT statement_timestamp();
      statement_timestamp      
-------------------------------
 2020-07-02 09:31:18.424503+10
(1 row)


postgres=# SELECT pg_sleep(5);
 pg_sleep 
----------
 
(1 row)


postgres=# SELECT statement_timestamp();
      statement_timestamp      
-------------------------------
 2020-07-02 09:31:23.501539+10
(1 row)


postgres=# COMMIT;
COMMIT

In this example I used the pg_sleep() function to delay execution between each statement.

Because each statement_timestamp() call was in its own SQL statement, the timestamp returned was different with each call.

This is in contrast to transaction_timestamp(), which doesn’t change with each statement. It returns its timestamp based on the start time of the transaction.

Multiple Calls within a Statement

Here’s an example of what happens if we combine all three function calls within a single SQL statement.

\x
SELECT 
  statement_timestamp(),
  pg_sleep(5),
  statement_timestamp(),
  pg_sleep(5),
  statement_timestamp();

Result (using vertical output):

statement_timestamp | 2020-07-02 09:34:41.06911+10
pg_sleep            | 
statement_timestamp | 2020-07-02 09:34:41.06911+10
pg_sleep            | 
statement_timestamp | 2020-07-02 09:34:41.06911+10

This time, all three timestamp values are identical, even though the pg_sleep() function was used to delay execution between each call to statement_timestamp().

This is in contrast with the clock_timestamp() function, which changes even as it progresses through the statement (if called multiple times within the statement).