CAST¶
The CAST function is used to convert a value from one data type to another. It is commonly used when you need to change the data type of a value or a column to perform a specific operation, such as arithmetic or string concatenation.
Syntax¶
expression: The value or column you want to convert.data_type: The target data type to which you want to convert the expression.
Examples¶
Converting a value to a different data type¶
In this example, the CAST function is used to convert the string 'TRUE' to a boolean value.
Converting a column to a different data type¶
Suppose you have a table called employees with the following structure:
To calculate the total salary of all employees, you can use the CAST function to convert the salary column to a DECIMAL data type:
Handling NULL values¶
The CAST function can handle NULL values as well. If the expression is NULL, the result will be NULL:
This query will return a NULL value.
Converting a value to a DATE or TIME data type¶
The CAST function can also be used to convert strings to DATE or TIME data types:
These queries will return a date and time value, respectively.
Limitations and Errors¶
Some conversions may be impossible or result in an error. For example, trying to convert a non-numeric string to an integer will result in an error:
This query will produce an error because the string 'foo' cannot be converted to an integer.