MySQL | CAST( ) Function

The MySQL CAST() function is used for converting a value from one datatype to another specific datatype. The CAST() function accepts two parameters which are the value to be converted and the datatype to which the value needs to be converted.

The datatypes in which a given value can be converted are:

  • DATE : It is used to convert a value to the DATE datatype. The Format returned is “YYYY-MM-DD”.
  • DATETIME : It is used to convert a value to the DATETIME datatype. The Format returned is “YYYY-MM-DD HH:MM:SS”.
  • TIME : It is used to convert a value to the TIME datatype. The Format returned is “HH:MM:SS”.
  • CHAR : It is used to convert a value to the CHAR datatype.
  • SIGNED : It is used to convert a value to SIGNED datatype.
  • UNSIGNED : It is used to convert a value to UNSIGNED datatype.
  • BINARY : It is used to convert a value to BINARY datatype.

Syntax:

CAST(input_value AS datatype)

Parameters Used:

  • input_value – It is used to specify the value which needs to be converted.
  • datatype – It is used to specify the datatype in which the value needs to be converted.

Return Value:
The MySQL CAST() function returns a value in the desired datatype after conversion.



Supported Versions of MySQL:

  • MySQL 5.7
  • MySQL 5.6
  • MySQL 5.5
  • MySQL 5.1
  • MySQL 5.0
  • MySQL 4.1
  • MySQL 4.0
  • MySQL 3.23

Example-1: Implementing CAST() function to convert a value to DATE datatype.

SELECT CAST("2019-11-21" AS DATE); 

Output:

2019-11-21 

Example-2: Implementing CAST() function to convert a value to CHAR datatype.

SELECT CAST(121 AS CHAR); 

Output:

121 

Example-3: Implementing CAST() function to convert a value to SIGNED datatype.

SELECT CAST(2-4 AS SIGNED); 

Output:

-2 

Example-4: Implementing CAST() function to convert a value to UNSIGNED datatype.

SELECT CAST(2-4 AS UNSIGNED); 

Output:

18446744073709551614 
My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.