gotchasqlMinor
Postgres strange conversion of the string 'now' to timestamp
Viewed 0 times
conversionthepostgresstrangenowtimestampstring
Problem
It looks like postgres treats the string
Why does postgres allow this?
or this?
or even this?
It does not give this "a string is the same as a function" treatment to other functions such as
DB fiddle
'now()' the same as a call to the now() function.Why does postgres allow this?
select 'now'::timestamp;or this?
select 'now()'::timestamp;or even this?
select ' ( ( ))) now)('::timestamp;It does not give this "a string is the same as a function" treatment to other functions such as
clock_timestamp().DB fiddle
Solution
'now' (with any amount of leading and trailing spaces and brackets ({[( )]}, which is trimmed as noise) is a special date/time input constant. It evaluates to the timestamp of the current transaction.If you find this one strange, you should try
SELECT 'allballs'::time; some time. :)now() (without single quotes, and exactly one pair of trailing parentheses), on the other hand, is a function, evaluated at execution time.Both just happen to use the same English word, because they return the "current time". But both are very different in nature.
The difference becomes evident when you use either as column default. The first one cements the timestamp of the transaction setting the column default. The second one evaluates to the timestamp of the transaction inserting a new row dynamically. (Typically, you want the second.)
See:
- Difference between now() and current_timestamp
Context
StackExchange Database Administrators Q#333806, answer score: 9
Revisions (0)
No revisions yet.