SQL CAST Function

The SQL CAST function is mainly used to convert the expression from one data type to another data type. If the SQL Server CAST function is unable to convert a declaration to the desired data type, this function returns an error. We use the CAST function to convert numeric data into character or string data.

Syntax:

Here, the [data type] is a type of valid data types in RDBMS.

The syntax is:

  • Expression: It is a valid expression where we want to convert a data type into the SQL.
  • Data_type: It is a Data Type to which we want to convert the expression.
  • Length: It is the optional parameter of an integer type. We can use the setting to define the length of any targeted data type.

By default, it is 30.

Examples:

Here, we will use the below tables.

Table Manager _ Score

Column NameDate Type
Manager IdInteger
First _ Namechar( 20)
Scorefloat

The table contains the following rows:

Table Manager_Score

ManagerIDFirst_NameScore
1Jame92.2
2Boby87.5
3Marry70
4Sanju120.2

Example 1:

Result:

First_NameInt_Score
Jame92
Boby87
Marry70
sanju120

In Example 1, we are using the CAST function to convert the SCORE column from type FLOAT to INTEGER. When we do it, various RDBMS have many rules to handle the numbers to the point of decimal.

According to the above example, the numbers after the decimal point are truncated.

Example 2:

Result:

First__NameChar__Score
Jame85.
Boby92.
Marry90
sanju110

In Example 2, we use the CAST function to convert the SCORE column from type FLOAT to CHAR (3). When we do it, we only hold the first 3 character. If there are more than three characters, everything after the first three characters is discarded.


Next TopicSQL Tutorial




Latest Courses