MySQL CAST() Function
The CAST() function in MySQL is used to convert a value from one data type to another data type specified in the expression. It is mostly used with WHERE, HAVING, and JOIN clauses. This function is similar to the CONVERT() function in MySQL.
The following are the datatypes to which this function works perfectly:
The following are the syntax of CAST() function in MySQL:
This syntax accepts two parameters, which are going to be discussed below:
After conversion, it will return a value in which data type we want to convert.
MySQL version support
The CAST function can support the following MySQL versions:
Let us understand the MySQL CAST() function with the following examples. We can use the CAST function with the SELECT statement directly.
This statement converts the value into DATE datatype.
This statement converts the value into SIGNED datatype.
This statement converts the value into UNSIGNED datatype.
Sometimes there is a need to convert the string into an integer explicitly, use the following statement for converting the value into INTEGER datatype.
The following statement first converts an integer value into string datatype and then perform concatenation with another specified string.
In this example, we are going to see how the CAST function works with the table. Let us first create a table "Orders" that contains the following data:
In the above table, we can see that the Order_Date is in DATE datatype. Now, if we want to get a product name between selected ranges of time, execute the statement below. Here, the literal string converted into timestamp value before evaluating the WHERE condition.
This statement will produce the following output: