SQL CAST Function
SQL > SQL String Functions >
In many cases, a database will automatically convert one data type into another when needed. On the other hand, there are instances when that is not the case, or when you want to explicitly specify what data type to change into. In these cases, you can use the CAST function. The syntax of the CAST function is as follows:
CAST (expression AS [data type])
where [data type] is a valid data type in the RDBMS you are working with.
Let's go through some examples to see how the CAST function is used. Assume we have the following table:
and this table contains the following rows:
SELECT First_Name, CAST(Score AS Integer) Int_Score FROM Student_Score;
In Example 1, we use the CAST function to convert the Score column from type FLOAT to INTEGER. When we do this, different RDMBS have different rules on how to handle the numbers after the decimal point. In the above example, we assume that the numbers after the decimal point are always truncated.
SELECT First_Name, CAST(Score AS char(3)) Char_Score FROM Student_Score;
In Example 2, we use the CAST function to convert the SCORE column from type FLOAT to CHAR(3). When we do this, we only take the first 3 characters. So, if there are more than 3 characters, everything after the first 3 characters is discarded.