The CAST() function in MySQL is used to explicitly convert a value from one data type to another. This is helpful when you need to ensure that a value is treated as a specific type, such as converting a string to a number or a date.
Syntax:
CAST(expression AS target_data_type)
Parameters:
expression: The value or column to be converted.target_data_type: The data type to convert the expression to. Examples includeCHAR,DATE,DATETIME,SIGNED,UNSIGNED,DECIMAL, etc.
Commonly Used Data Types:
- String types:
CHAR(n)orCHAR - Numeric types:
SIGNED,UNSIGNED,DECIMAL(n, d) - Date/Time types:
DATE,DATETIME,TIME
Examples:
1. Convert a number to a string:
SELECT CAST(12345 AS CHAR);
Output: '12345' (as a string)
2. Convert a string to a number:
SELECT CAST('12345' AS UNSIGNED);
Output: 12345 (as an integer)
3. Convert a string to a date:
SELECT CAST('2024-12-24' AS DATE);
Output: '2024-12-24' (as a date)
4. Convert to a decimal with precision:
SELECT CAST(12345 AS DECIMAL(10, 2));
Output: 12345.00
5. Using CAST() with a column:
SELECT name, CAST(age AS UNSIGNED) AS age_numeric FROM users;
This converts the age column to an unsigned integer.
Notes:
- If the conversion fails (e.g., converting non-numeric characters to a number), MySQL may return
0orNULLdepending on the context. - For implicit conversions, MySQL often converts data types automatically, but
CAST()allows for precise control.
Let me know if you'd like to see examples specific to your use case!
No comments:
Post a Comment