PostgreSQL Current_Timestamp Function: How to Use It
In this article
The PostgreSQL current_timestamp function returns the current date and time with time zone, as of the start of the current transaction. It is a stable value within a transaction, meaning it does not change if called multiple times during the same transaction — unlike now(), which behaves the same way, or clock_timestamp(), which updates with each call. No setup is required beyond having PostgreSQL installed and access to a database.
What You'll Need
- A running PostgreSQL server (version 9.0 or later)
- Access to a database via a client such as psql, pgAdmin, DBeaver, or any SQL-compatible interface
- Basic permissions to execute SELECT statements (no special roles needed)
Step-by-Step
- Open your PostgreSQL client. If using the command line, type
psql -U your_username -d your_databaseand enter your password when prompted. - Start a transaction by entering
BEGIN;— this ensures you can observe howcurrent_timestampbehaves within a transaction block. (This step is optional but recommended for understanding.) - Execute
SELECT current_timestamp;and press Enter. The result will display the current date and time with time zone, for example:2024-06-15 10:32:45.123456-07. - Wait a few seconds, then execute
SELECT current_timestamp;again within the same transaction. You will see the exact same value, confirming it is transaction-stable. - Compare this to
SELECT clock_timestamp();— you will notice the time has advanced, showing thatclock_timestamp()updates with each call. - To use
current_timestampin an INSERT statement, write:INSERT INTO logs (event_time, message) VALUES (current_timestamp, 'User logged in');. This automatically records the transaction start time. - To alter a table column to use
current_timestampas a default, run:ALTER TABLE orders ALTER COLUMN created_at SET DEFAULT current_timestamp;. Existing rows keep their old values; new rows will auto-fill with the transaction time. - To verify the default is set correctly, insert a new row without specifying
created_at:INSERT INTO orders (customer_id) VALUES (123);, then runSELECT created_at FROM orders WHERE customer_id = 123;to see the auto-filled timestamp. - Exit the transaction with
COMMIT;orROLLBACK;depending on whether you want to save changes.
Common Mistakes
- Confusing
current_timestampwithclock_timestamp()— the former is stable per transaction, the latter changes with every call. Usingclock_timestamp()when you need consistency can cause unexpected behavior in logs or audits. - Assuming
current_timestampreflects the system clock of the server — it reflects the transaction start time, which may differ from wall-clock time if the transaction was delayed or held. - Trying to use
current_timestampas a function argument in a WHERE clause expecting real-time updates — it will return the same value throughout the query, even if executed across multiple rows. - Forgetting to set a column’s default value properly — if you write
DEFAULT now()instead ofDEFAULT current_timestamp, the behavior is identical, butcurrent_timestampis more explicit and standard-compliant. - Using
current_timestampin a trigger or stored procedure without understanding transaction boundaries — if the trigger fires multiple times in one transaction, all instances return the same timestamp.
Tips
- Use
current_timestampfor audit trails, order creation times, and any event that should be tied to the start of a logical unit of work. - When designing tables for high-concurrency systems, prefer
current_timestampover manually inserting timestamps — it avoids client-side clock skew and reduces network round-trips. - Combine
current_timestampwithtimezone('UTC', current_timestamp)to explicitly convert to UTC if your app expects all times in one zone. - For logging systems, consider adding
created_at TIMESTAMPTZ DEFAULT current_timestampto every table that tracks events — it’s declarative, efficient, and self-documenting. - Always test timestamp behavior in transactions. Run two SELECTs 10 seconds apart inside BEGIN/COMMIT to confirm stability.
- Use
EXPLAIN ANALYZEto see if your queries are relying on stable timestamps — this can help optimize batch inserts or data migrations.
Troubleshooting
- Query returns NULL: Check if you’re using
current_timestampin a context where it’s not valid, such as a CHECK constraint or as a column type. It must be used in a SELECT, INSERT, UPDATE, or DEFAULT clause. - Time zone appears incorrect: Your client or database may be set to a different time zone. Run
SHOW timezone;to check the server’s time zone setting. Adjust withSET timezone TO 'America/Los_Angeles';if needed. - Timestamp format is unreadable: Use
TO_CHAR(current_timestamp, 'YYYY-MM-DD HH24:MI:SS')for custom formatting. Avoid relying on default display — it varies by client. - Transaction not starting: Ensure you’re not in auto-commit mode (default in most clients). In psql,
\echo :AUTOCOMMITshows the setting. Use\set AUTOCOMMIT offto disable if testing transaction stability. - Default not applying on INSERT: Verify the column was altered correctly. Run
\d your_tablein psql to see column definitions. Ensure no explicit NULL was passed in the INSERT statement. - Different results between sessions: This is normal. Each transaction has its own start time. If you need synchronized time across clients, consider using a single authoritative source like
clock_timestamp()— but understand it’s not transaction-stable.
Frequently Asked Questions
Is current_timestamp the same as now() in PostgreSQL?
Yes,current_timestamp and now() are functionally identical. Both return the transaction start time with time zone. Use either — current_timestamp is ANSI SQL standard, while now() is PostgreSQL-specific.
Can I update current_timestamp in an existing row?
No. It is a function, not a mutable value. To update a timestamp column, you must explicitly assign a new value likeUPDATE table SET updated_at = current_timestamp WHERE id = 1;.
Does current_timestamp change if the server clock is adjusted?
No. It captures the time at transaction start and remains fixed for the duration of that transaction, regardless of system clock changes.What’s the difference between current_timestamp and localtimestamp?
current_timestamp includes time zone info (timestamptz), while localtimestamp returns a timestamp without time zone (timestamp). Use current_timestamp for global applications; use localtimestamp only if you’re certain the application handles time zones separately.
Can I use current_timestamp in a WHERE clause for time-based filtering?
Yes, but be aware it returns the transaction start time, not the current moment. For example,WHERE created_at > current_timestamp - interval '1 hour' is valid and common — it filters records from the last hour relative to the transaction start.
Why does my timestamp show microseconds when I only want seconds?
PostgreSQL defaults to microsecond precision. To truncate, usedate_trunc('second', current_timestamp). For example: SELECT date_trunc('second', current_timestamp); returns 2024-06-15 10:32:45 without fractions.