MySQL CAST

The CAST function in MySQL is used to convert a value from one data type to another. It is useful when you need to manipulate data types for calculations or formatting.

Examples with Tamil Kings

1. Casting an Integer to a String

SELECT king_name, CAST(reign_years AS CHAR) AS reign_years_string FROM tamil_kings_auto_increment;

Code Explanation: This query converts reign_years from an integer to a string using CAST and renames the result as 'reign_years_string'.

2. Casting a String to a Decimal

SELECT CAST('1234.56' AS DECIMAL(10, 2)) AS decimal_value;

Code Explanation: This query converts the string '1234.56' to a decimal value with two decimal places.

Best Practices

  • Use CAST for explicit data type conversions to avoid errors.
  • Be mindful of data loss when converting to a different type, such as truncation when converting to integers.

Key Takeaways

  • The CAST function converts a value from one data type to another.
  • It is useful for ensuring data type compatibility in calculations and formatting.