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.
SQL CAST
The CAST() function converts a value (of any type) into a specified datatype.
Syntax
CAST (expression AS type [ (length)])
Parameters
- 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.
Note
- 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.
Examples
SELECT CAST (10.85 AS int);
Output
10
Explanation
As the expression is converted from float to integer. So, the result here is truncated.
Query 2
SELECT CAST (10.85 AS float);
Output
10.85
Explanation
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.
Query 3
SELECT CAST (15.6 AS varchar);
Output
'15.6'
Explanation
Here, the floating expression was converted to character datatype.
Query 4
SELECT CAST ('15.6' AS float);
Output
15.6
Explanation
Here, the character data type is converted to a floating-point value.
Query 5
SELECT CAST (5.95 AS DEC (3,0));
Output
6
Explanation
Here, the decimal expression is converted to another decimal expression with different lengths.
Query 6
SELECT CAST ('2020-02-26' AS datetime);
Output
'2020-02-26 00:00:00.000'
Explanation
Here, the string expression is converted to datetime expression.