Type conversion functions, CAST
When we perform operations on values with different data types, the DBMS tries to perform a conversion and cast the values used to the desired type. For example, in the example below we are comparing values with STRING and INT types. To perform this MySQL comparison automatically will convert a string value to a numeric value.
SELECT '50' > 49, '50' > 51;
But not all DBMS conversions can be done automatically, and then it is necessary to do an explicit type conversion. To do this, MySQL has two very similar functions CAST and CONVERT.
Syntax
CAST(value AS conversion_type); CONVERT(value, conversion_type);
Example,
SELECT CAST(12005.6 AS DECIMAL), CONVERT(12005.4, DECIMAL);
The CAST function can convert the passed value to any of the following types:
Impossibility of any conversion
Using the CAST function imposes requirements on the format of the original value. And the question immediately arises, what happens if the given format does not match the required one? For example, if you try to convert random text to a temporary data type:
SELECT CAST('SQL Academy' AS DATETIME);
In this case, MySQL will return NULL instead of the converted value.
Self test
So, what is the responsibility of the CAST function in SQL 🧐?