TIMESTAMP <string-literal>

Started by John Lumbyalmost 6 years ago2 messagesdocs
Jump to latest
#1John Lumby
johnlumby@hotmail.com

I am curious about the syntactic nature of the expression :

TIMESTAMP '2020-07-13'

in this expression,  is the token TIMESTAMP a function, typecast,  or other?

I don't see a description of it as a function and there are no
parentheses in this example.

But this expression also doesn't seem to conform to the described forms
for a typecast.

I do see this text in the description of typecast :

-----------------------------------------------------------------------------------------------------

It is also possible to specify a type cast using a function-like syntax:

typename ( expression )

-----------------------------------------------------------------------------------------------------

which also lists some types which can be used this way,  including
timestamp, but this description implies that parentheses are mandatory
and also says that in the case of timestamp the name must be double-quoted.

I also tried

FLOAT8 '7.3'

and that is accepted as well.     So maybe the above syntax description
should indicate that parentheses are optional?

Or if not,  where in the documentation is this syntax described?

Cheers,   John Lumby

#2Tom Lane
tgl@sss.pgh.pa.us
In reply to: John Lumby (#1)
Re: TIMESTAMP <string-literal>

J Lumby <johnlumby@hotmail.com> writes:

I am curious about the syntactic nature of the expression :
TIMESTAMP '2020-07-13'
in this expression, is the token TIMESTAMP a function, typecast,  or other?
I don't see a description of it as a function and there are no
parentheses in this example.

This construct is a typed constant, as described at
"4.1.2.7. Constants Of Other Types" on this page:

https://www.postgresql.org/docs/current/sql-syntax-lexical.html

It's a wart, frankly, and we wouldn't have it if the SQL standard
didn't insist. Of the three syntaxes described by 4.1.2.7:

type 'string'
'string'::type
CAST ( 'string' AS type )

the second and third actually work for casting any expression,
but the first one *only* works for a literal-string constant.
People are constantly burnt by that, for example by expecting
that they can write

TIMESTAMP $1

You can plug a parameter symbol into the other two syntaxes,
but not that one. On the whole I prefer using 'string'::type,
which is slightly more typing effort, but it generalizes correctly.

I also tried
FLOAT8 '7.3'
and that is accepted as well.

IIRC, the SQL standard only defines this syntax for certain types
such as TIMESTAMP and INTERVAL; but Postgres allows it for any
type name.

regards, tom lane