Now Versus clock_timestamp In Transactions

now() freezes at transaction start so every call in one transaction agrees, while clock_timestamp() keeps moving with the wall clock.

SqlData Integrity

Code

snippet
-- now() 与 transaction_timestamp() 同义:冻结在事务开始时刻
BEGIN;

SELECT
    now()             AS txn_clock,
    clock_timestamp() AS wall_clock,
    statement_timestamp() AS stmt_clock
FROM (VALUES (1)) AS t(x);

-- 同一事务再查一次:txn_clock 与上一条完全相同,
-- wall_clock / stmt_clock 则随真实时间继续走
SELECT
    now()             AS txn_clock_again,
    clock_timestamp() AS wall_clock_again
FROM (VALUES (1)) AS t(x);

COMMIT;

How it works

One transaction, two queries, three clocks. BEGIN; opens the transaction and the first SELECT reads all three timestamp functions side by side: now() AS txn_clock, clock_timestamp() AS wall_clock, and statement_timestamp() AS stmt_clock. Per the file’s comment, now() is synonymous with transaction_timestamp() and is frozen at the moment the transaction started.

The second SELECT runs inside the same transaction and reads now() again as txn_clock_again plus clock_timestamp() AS wall_clock_again. The comment states the expected contrast: txn_clock_again matches the first query’s value exactly, while the wall-clock and statement clocks keep advancing with real time. COMMIT; closes the transaction.

What to watch for

  • The demonstrated rule: every call to now() inside one transaction agrees, because the value is fixed at transaction start; clock_timestamp() can differ on every call — the file’s comment recommends it when you need to measure real elapsed time.
  • statement_timestamp() is included in the first query as the third reference point.

Using it

The comparison only means something inside an explicit BEGIN/COMMIT pair — the file runs both queries in one transaction so the frozen-versus-moving contrast is visible between txn_clock and txn_clock_again.

Key statements

SELECT
now()             AS txn_clock,
clock_timestamp() AS wall_clock,
statement_timestamp() AS stmt_clock
FROM (VALUES (1)) AS t(x);
SELECT
now()             AS txn_clock_again,
clock_timestamp() AS wall_clock_again
FROM (VALUES (1)) AS t(x);

Interactive Tools for This Topic