How the CHR() function works in Mariadb?

The MariaDB CHR() function is used to convert an ASCII code integer to its corresponding character.

Posted on

The MariaDB CHR() function is used to convert an ASCII code integer to its corresponding character. This function can be particularly useful when you need to generate characters from their ASCII values or when performing data transformations and encoding.

Syntax

The syntax for the MariaDB CHR() function is as follows:

CHR(ascii_val)

Where ascii_val is an integer representing the ASCII code of the character to be returned.

Examples

Example 1: Basic Character Conversion

To convert an ASCII code to its corresponding character:

SELECT CHR(65);
+---------+
| CHR(65) |
+---------+
| A       |
+---------+

The output is A, which is the character with ASCII code 65.

Example 2: Non-Printable Character

Here’s how to get a non-printable character from an ASCII code:

SELECT CHR(7);
+--------+
| CHR(7) |
+--------+
|       |
+--------+
(Bell character)

The output is the bell character, which is a non-printable control character.

Example 3: Using CHR() in a String Concatenation

To concatenate characters into a string:

SELECT CONCAT(CHR(72), CHR(101), CHR(108), CHR(108), CHR(111));
+---------------------------------------------------------+
| CONCAT(CHR(72), CHR(101), CHR(108), CHR(108), CHR(111)) |
+---------------------------------------------------------+
| Hello                                                   |
+---------------------------------------------------------+

The output is Hello, created by concatenating the characters with ASCII codes 72, 101, 108, 108, and 111.

Example 5: Generating a Range of Characters

Let’s generate a range of characters using CHR():

SELECT CHR(a.ascii_val) FROM (
    SELECT 65 AS ascii_val
    UNION ALL SELECT 66
    UNION ALL SELECT 67
) AS a;
+------------------+
| CHR(a.ascii_val) |
+------------------+
| A                |
| B                |
| C                |
+------------------+

The output is a sequence of characters A, B, and C, corresponding to their ASCII codes.

  • The ORD() function is used to get the ASCII code of the first character of a string.
  • The ASCII() function is similar to ORD() but is specifically designed to work with single characters.
  • The CHAR_LENGTH() function is used to return the number of characters in a string.

Conclusion

The CHR() function in MariaDB is a simple yet powerful tool for converting ASCII codes to their respective characters. It is widely used in data manipulation, encoding, and when working with character sets. Understanding how to use the CHR() function expands the capabilities of database developers and analysts in processing and presenting data effectively.