Explain Codes LogoExplain Codes Logo

From Now() to Current_timestamp in PostgreSQL

sql
timestamp
postgresql
database-operations
Nikita BarsukovbyNikita Barsukov·Dec 28, 2024
TLDR

In PostgreSQL, both NOW() and CURRENT_TIMESTAMP fetch the current timestamp. However, CURRENT_TIMESTAMP aligns with the official SQL standard. These functions denote the start time of the ongoing transaction.

Example:

SELECT CURRENT_TIMESTAMP;

The result should coincide with NOW(), reflecting the timestamp of the transaction initiation.

Keep timestamp comparisons accurate by using INTERVAL for mathematical operations involving time. Defaulting to integers could lead to unexpected results or errors.

Nailing timestamp mechanics

Timestamps play a significant role in consistent and accurate data operations in PostgreSQL. Delving into NOW() and CURRENT_TIMESTAMP, we find transaction-bound timestamps. For timestamp arithmetic or comparisons, the correct syntax and data types are key.

When you need to perform timestamp arithmetic, use something like this:

SELECT CURRENT_TIMESTAMP - INTERVAL '1 day'; --Minus a day, keep the change

Here, you're subtracting one day from the current timestamp using the correct INTERVAL. Remember, integers can't moonlight as intervals! Pretending that they can leads to the dreaded "operator does not exist" error.

Crossing database borders

Transitioning from MySQL to PostgreSQL? The devil is in the detail. While NOW() appears consistent cross-platform, slight variations in behaviour and syntax demand consultation with PostgreSQL documentation.

Here's the translation for a timestamp computation example:

-- MySQL SELECT DATE_ADD(NOW(), INTERVAL 1 DAY); -- PostgreSQL SELECT NOW() + INTERVAL '1 day'; --Adds a day faster than Superman can put on PJs

Refining timestamp comparisons

During intricate queries or joins, use specific table references. When dealing with timestamp comparisons, specify your table and column to alleviate confusion:

SELECT a.created, b.updated FROM table_a a JOIN table_b b ON a.created::date = b.updated::date; --Strictly catered table meeting

Clear queries equate to smooth debugging and accurate operations.