Similar method like TRY_CAST in presto

8.8k views Asked by At

In SQL server, there is TRY_CAST method available to check if cast is possible or not. If cast is not possible then it will set NULL as value.

Is there any similar method available in presto? Or How to achieve similar behavior in presto?

2

There are 2 answers

0
Martin Traverso On

That function has existed for many years. You can find it in the docs.

SELECT try_cast('abc' AS bigint)

=>

 _col0
-------
  NULL
(1 row)
0
Chris Hang On

I tried to use TRY_CAST to convert a string into a timestamp and compare it with my own converting code.

select 
CASE
 WHEN LENGTH(received)<3 
   THEN NULL
 ELSE DATE(DATE_PARSE(substr(received, 1,10), '%m/%d/%Y'))  
 END AS "RECEIVED_CV"
,DATE(TRY_CAST(received AS TIMESTAMP)) AS RECEIVED
from (table)

The result is very interesting. My code will produce the date but the TRY_CAST will produce null. The original string value is like this "02/05/2021 15:45:57.000000"

Comparison of the results