SQL CAST Function Example
SQL CAST is an inbuilt function that is used for converting an expression from one data type to another data type. Here, if the conversion takes place, then a value with specified conversion will be returned. Otherwise, the function will return an error.
The CAST() function converts a value (of any type) into a specified datatype.
CAST (expression AS type [ (length)])
- Expression: The value to be converted to another datatype.
- Type: The data type to which the expression will be converted.
- Length: It is entirely optional. It signifies the length of the resulting data type for expression.
- The result is truncated when an expression is converted to integer datatype when converted from float or integer.
- For other conversions, the value is rounded.
SELECT CAST (10.85 AS int);
As the expression is converted from float to integer. So, the result here is truncated.
SELECT CAST (10.85 AS float);
As the expression is converted to float datatype. So, the result here is not truncated, and the original expression was returned, which was already in the float.
SELECT CAST (15.6 AS varchar);
Here, the floating expression was converted to character datatype.
SELECT CAST ('15.6' AS float);
Here, the character data type is converted to a floating-point value.
SELECT CAST (5.95 AS DEC (3,0));
Here, the decimal expression is converted to another decimal expression with different lengths.
SELECT CAST ('2020-02-26' AS datetime);
Here, the string expression is converted to datetime expression.