Tuesday, December 24, 2024

MySQL CONVERT() Function

 The CONVERT() function in MySQL is used to convert a value from one data type to another. It can also be used to convert between character sets.

Syntax:

  1. Basic Syntax for Data Type Conversion:

    CONVERT(expression, target_data_type)
    
    • expression: The value to be converted.
    • target_data_type: The data type to convert the expression to (e.g., CHAR, SIGNED, DATE, DATETIME, etc.).
  2. Syntax for Character Set Conversion:

    CONVERT(expression USING character_set_name)
    
    • expression: The string to be converted.
    • character_set_name: The name of the character set to convert the expression to (e.g., UTF8, LATIN1).

Examples:

1. Convert a string to an integer:

SELECT CONVERT('123', SIGNED);

This will return 123 as an integer.

2. Convert a date string to a DATE data type:

SELECT CONVERT('2024-12-24', DATE);

This will return the value as a DATE type.

3. Convert a string to a specific character set:

SELECT CONVERT('Hello' USING utf8);

This converts the string 'Hello' into the UTF-8 character set.

4. Convert a number to a string (character type):

SELECT CONVERT(1234, CHAR);

This converts the integer 1234 to a string '1234'.

5. Convert between date and string:

SELECT CONVERT('2024-12-24 15:30:00', DATETIME);

This will return a DATETIME value.

Notes:

  • The CONVERT() function can be used to manipulate data formats, especially when you need to store or display values in different formats.
  • It can also handle character set conversions, useful when working with data stored in multiple languages or encodings.

Let me know if you need more details or examples!

No comments:

Post a Comment