Would there be much difference if I used CAST instead of SELECT CAST or SELECT SAFE_CAST? Thank you in advance.
I'm having trouble understanding when to use these. I understood CAST but then I learned SELECT CAST and SELECT SAFE_CAST wondering if there are kinds of scenarios when it's only applicable to use SELECT SAFE_CAST or SELECT CAST.
SAFE_CASTis best used if there is a likelihood of a casting error for example if converting strings to dates the string31-Feb-2023cannot be converted to a date. In this caseSAFE_CASTreturns a NULL and allows the query to proceed. In the final output the user may then inspect all cases where the conversion resulted in NULL and perhaps correct the input to a proper date. UsingCASTalone would just produce an error message and you would probably not know which row caused the error. e.g.However, this will crash because some strings just cannot be converted into a date:
In the opposite direction, if we have a column of a specific data type and wish to convert that to strings then you don't require safe_cast:
although it is more likely you would format e.g.
Perhaps try the above SQL at https://dbfiddle.uk