PostgreSQL – STATEMENT_TIMESTAMP

The statement_timestamp() function is used to retrieve the timestamp when the current statement within a transaction started. Unlike transaction_timestamp(), which gives you the timestamp when the transaction started (and remains constant throughout the transaction), statement_timestamp() provides the timestamp specific to the current SQL statement being executed. This can be useful for recording when individual statements were executed within a transaction.

Here’s how you can use the statement_timestamp() function in PostgreSQL:

SELECT statement_timestamp();

This SQL statement will return the current timestamp at the start of the current SQL statement.

For example, you can use it to record when a specific SQL statement was executed within a transaction:

-- Start of the transaction 
BEGIN; 
-- Execute SQL statement 1 
INSERT INTO your_table (timestamp_column, data) VALUES (statement_timestamp(), 'Statement 1 data'); 
-- Execute SQL statement 2 
UPDATE another_table SET timestamp_column = statement_timestamp() WHERE condition; 
-- Commit the transaction 
COMMIT;

In the example above, statement_timestamp() is used within each SQL statement to record the timestamp when that specific statement was executed. This can be particularly helpful when you want to track the timing of individual actions or events within a transaction.

Similar Posts