This tutorial explains how to use the MySQL CAST function with syntax and examples.
The MySQL CAST function converts a value from one datatype to another datatype.
The syntax for the CAST function in MySQL is:
The value to convert to another datatype.
The datatype that you wish to convert value to. It can be one of the following:
Value | Description |
---|---|
DATE | Converts value to DATE type, which has a date portion only. Format is 'YYYY-MM-DD'. Supported range is '1000-01-01' to '9999-12-31'. |
DATETIME | Converts value to DATETIME type, which has both date and time portions. Format is 'YYYY-MM-DD HH:MM:SS'. Supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'. |
TIME | Converts value to TIME type, which has a time portion only. Format is 'HH:MM:SS'. Supported range is '-838:59:59' to '838:59:59'. |
CHAR | Converts value to CHAR type, which is a fixed length string. |
SIGNED | Converts value to SIGNED type, which is a signed 64-bit integer. |
UNSIGNED | Converts value to UNSIGNED type, which is an unsigned 64-bit integer. |
BINARY | Converts value to BINARY type, which is a binary string. |
The CAST function can be used in the following versions of MySQL:
Let's look at some MySQL CAST function examples and explore how to use the CAST function in MySQL.
The first CAST function example shows how to cast a value to a DATE type. For example:
This CAST example takes the value '2014-02-28' and casts it as a DATE datatype.
This CAST function example shows how to cast a value to a DATETIME type. For example:
This CAST example takes the value '2014-02-28 08:14:57' and casts it as a DATETIME datatype.
This CAST function example shows how to cast a value to a TIME type. For example:
This CAST example takes the value '08:14:57' and casts it as a TIME datatype.
This CAST function example shows how to cast a value to a CHAR type. For example:
This CAST example takes the value 125 and casts it as a CHAR datatype with the value of '125'.
This CAST function example shows how to cast a value to a SIGNED type. For example:
This CAST example takes the value 4-5 and casts it as a SIGNED datatype with the value of -2.
This CAST function example shows how to cast a value to an UNSIGNED type. For example:
This CAST example takes the value 4-5 and casts it as an UNSIGNED datatype with the value of 18446744073709551614.
This CAST function example shows how to cast a value to a BINARY type. For example:
This CAST example takes the value '4' and casts it as a BINARY datatype with the binary string value of '4'.