SQL Cast Function
Let us explore.
The function syntax is as shown:
The function arguments are as follows:
- expr – defines the value or expression you wish to convert to another type.
- target_type – sets the target data type to which you wish to convert. Accepted data types include int64, numeric, bignumeric, float64, bool, string, bytes, data, datetime, array, struct, time, and timestamp.
The function returns the input expression as the target data, data type.
The following example shows how to convert from strings to various data types.
This should return the values as follows:
Example 2 – Convert String to Date
The example below shows how to use the cast() function to convert a string to a date type.
Example 3 – Using String to Datetime
The example below uses the cast() function to convert the value to datetime.
Example 2 – Converting Int to Bool
In the example below, the cast() function allows us to convert the int 0 to FALSE and the int 1 and above to TRUE.
In this post, we covered the basics of working with the cast() function in Standard SQL to convert a given expression to another data type.
Thanks for reading. Check out our other SQL tutorials to learn more.