Last Updated : 12 May, 2023
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:
Syntax:
CAST(input_value AS datatype)
Parameters Used:
Return Value: The MySQL CAST() function returns a value in the desired datatype after conversion. Supported Versions of MySQL:
Example 1:
Implementing CAST() function to convert a value to DATE datatype.
SELECT CAST("2023-04-19" AS DATE);
Output:
Example 2:
Implementing CAST() function to convert a value to CHAR datatype.
SELECT CAST(121 AS CHAR);
Output:
Example 3:
Implementing CAST() function to convert a value to the SIGNED datatype.
SELECT CAST(2-4 AS SIGNED);
Output:
Example 4:
Implementing CAST() function to convert a value to the UNSIGNED datatype.
SELECT CAST(2-4 AS UNSIGNED);
Output:
ExampleLet's assume that we have a table and we'll see how the CAST function interacts with the table in this example. Let's first create a table called "Orderss" with the following information in it:
Query:
CREATE TABLE Orderss ( OrderID int NOT NULL, CustomerName varchar(255) NOT NULL, OrderDate datetime NOT NULL ); INSERT INTO Orderss (OrderID, CustomerName, OrderDate) VALUES (1, 'John Doe', CAST('2023-03-15' AS datetime)); INSERT INTO Orderss (OrderID, CustomerName, OrderDate) VALUES (2, 'Jane Smith', CAST('2022-04-10' AS datetime)); INSERT INTO Orderss (OrderID, CustomerName, OrderDate) VALUES (3, 'Bob Johnson', CAST('2020e -05-20' AS datetime)); INSERT INTO Orderss (OrderID, CustomerName, OrderDate) VALUES (4, 'Alice Brown', CAST('2022-06-05' AS datetime));
Output:
Now, we will apply some operations to see how the output changes according to the given condition.
Query:
SELECT OrderID, CustomerName, OrderDate FROM Orderss WHERE (OrderDate) = 2022 ORDER BY OrderDate DESC;
Output:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4