SQL > SQL String Functions > CAST Function

The CAST function in SQL converts data from one data type to another. For example, we can use the CAST function to convert numeric data into character string data.

SQL CAST(expression AS data_type) is the ANSI-standard way to convert a value from one type to another — commonly used to convert numbers to strings, floats to integers, or dates to text.

Syntax

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.

Examples

We use the following table for our examples.

Table Student_Score

 Column Name  Data Type 
 StudentID  integer 
 First_Name  char(20) 
 Score  float 

This table contains the following rows:

Table Student_Score

 StudentID  First_Name  Score 
1Jenny 85.2 
2Bob 92.5 
3Alice 90 
4James 120.1 

Example 1

SELECT First_Name, CAST(Score AS Integer) Int_Score FROM Student_Score;

Result:

First_Name Int_Score
Jenny 85
Bob 92
Alice 90
James 120

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, the numbers after the decimal point are always truncated.

Example 2

SELECT First_Name, CAST(Score AS char(3)) Char_Score FROM Student_Score;

Result:

First_Name Char_Score
Jenny 85.
Bob 92.
Alice 90  
James 120

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 three characters. So, if there are more than three characters, everything after the first three characters is discarded.

Frequently Asked Questions

What does SQL CAST do?
CAST converts a value from its current data type to a specified target data type. It is part of the ANSI SQL standard and is available in virtually all relational databases.
Does CAST truncate or round when converting FLOAT to INTEGER?
This depends on the database. Most systems truncate (drop the fractional part) rather than round. For example, 85.9 may become 85. Check your RDBMS documentation for exact behaviour.
What is the difference between CAST and CONVERT?
CAST is ANSI SQL standard. CONVERT is a vendor-specific function (SQL Server, MySQL) that adds formatting options, especially for date and time conversions. Use CAST for cross-database compatibility.
Can I convert a number to a string with CAST?
Yes. Use CAST(number AS CHAR(n)) or CAST(number AS VARCHAR(n)). Only the first n characters are retained, so ensure n is large enough for all possible values.

Next: SQL CONVERT Function

This page was last updated on March 19, 2026.




Copyright © 2026   1keydata.com   All Rights Reserved     Privacy Policy     About   Contact