I have a table who has a column timestamp
which type is text
. Most of the rows have timestamp format as 2024-10-13T00:00:00.000Z
. But there are some rows have invalid timestamp value.
When I use this date_trunc
to aggregate the timestamp,
select date_trunc('hour', timestamp_candidate::timestamp) hourly
I got this error:
ERROR: invalid input syntax for type timestamp: "xxxxxx"
The invalid value could be anything including null
. Is there a way to skip any invalid values?
2
Answers
In PostgreSQL 16 and above, there’s
pg_input_is_valid()
:demo at db<>fiddle
it’s type
text
as
timestamp
note Special Date/Time Inputs are valid
Here’s what it skipped over. Thing to note is that a text literal
'null'
isn’t considered a valid input that would lead to a timestamp-typed field with anull
in it and a regularnull
yieldsnull
rather thantrue
orfalse
even thoughnull::timestamp
works fine.(it’s a midnight that’s missing a date)
From the doc:
In PostgreSQL 15 and earlier, you can build your own:
Note that this will return
false
regardless of whether the argument or the type is invalid, or both. Unlikepg_input_is_valid()
, it yieldstrue
fornull
, considering it a valid input for any type.Postgres does not have a corresponding function to Sql Server’s
try_cast()
function. But it is a simple matter to create a specific implementation (in this case for timestamp). The following is one such example: (see demo)Note: The function is susceptible to your
datestyle
setting.