MySQL CAST() Function
The CAST()
function in MySQL changes a value from one data type to another. This is a very useful function for data manipulation and ensuring your data is in the correct format for calculations, comparisons, or display.
CAST(): Definition and Usage
CAST()
is a flexible tool for converting data types. You specify the value or expression you want to convert and the new data type. This allows you to handle data from different sources or change the way data is stored within your database.
Syntax
Syntax
CAST(value AS datatype)
Parameter Values
Parameter | Description |
---|---|
value |
The value you want to convert. This is required. |
datatype |
The data type you want to convert to. Options: DATE , DATETIME , DECIMAL(M,D) , TIME , CHAR , NCHAR , SIGNED , UNSIGNED , BINARY . This is required. |
Examples
Converting to DATE
This example converts a string to a DATE value.
Syntax
SELECT CAST("2017-08-29" AS DATE);
Output
2017-08-29
Converting to CHAR
This converts a number to a character string.
Syntax
SELECT CAST(150 AS CHAR);
Output
150
Converting to TIME
Converting a string to a TIME value.
Syntax
SELECT CAST("14:06:10" AS TIME);
Output
14:06:10
Converting to SIGNED
Converting a numeric expression to a signed integer.
Syntax
SELECT CAST(5 - 10 AS SIGNED);
Output
-5