MySQL CAST Function
The CAST()
function in MySQL is used to convert a value from one data type to another. It is part of the SQL standard, making it a robust and flexible tool for data type conversions.
Syntax
expression
: The value or column to be converted.target_data_type
: The desired data type to which the value should be converted.
Supported Data Types
The CAST()
function supports the following target data types:
Numeric Types:
DECIMAL
,SIGNED
,UNSIGNED
String Types:
CHAR
,BINARY
,NCHAR
,CHARACTER
Date/Time Types:
DATE
,DATETIME
,TIME
JSON:
- Converts data to JSON format.
Examples
1. Casting to Numeric Types
Convert a string to a number:
Output: 123.45
2. Casting to String
Convert a numeric value to a string:
Output: '12345'
3. Casting to Date/Time Types
Convert a string to a DATE
:
Output: 2025-01-24
4. Casting to JSON
Convert a string to JSON:
Output: {"name": "John", "age": 30}
Using CAST()
in Queries
1. Using in SELECT Clause
Convert column data types for better readability or formatting:
2. Using in WHERE Clause
Compare data by converting types:
3. Using in GROUP BY
Ensure consistency in grouping by casting:
Key Considerations
Truncation or Rounding: When converting to numeric types, values may be truncated or rounded depending on the target type and precision.
Invalid Conversions: If the
CAST()
function cannot convert a value, it may result inNULL
or an error, depending on the context.Performance Impact: Conversions may add overhead to queries, especially when applied to large datasets.
Difference Between CAST()
and CONVERT()
Feature | CAST() | CONVERT() |
---|---|---|
SQL Standard | Compliant | Not SQL standard (MySQL-specific syntax). |
Syntax | CAST(expression AS type) | CONVERT(expression, type) |
Use Case | Preferred for portability. | Useful in MySQL-specific projects. |
Example with CONVERT()
:
Conclusion
The CAST()
function in MySQL is a powerful tool for converting data types within queries. Its versatility across numeric, string, date/time, and JSON formats makes it an essential function for data transformation and type compatibility in SQL operations.