How the ASCII() function works in Mariadb?

The ASCII() function is a string function that returns the ASCII code of the first character of a given string. The ASCII() function can be used to get the numeric value that represents a character in the ASCII encoding scheme.

Posted on

In the realm of databases, understanding how to manipulate and analyze string data is crucial. MariaDB offers a plethora of string functions, one of which is the ASCII() function. This function is instrumental in returning the ASCII value of the leftmost character of a string. Let’s explore the intricacies of the ASCII() function in MariaDB.

Syntax

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

ASCII(str)

Where str is the string argument for which the ASCII value of the leftmost character will be returned. The function returns an integer value that represents the ASCII code of the character. If the string is empty, it returns 0, and if it is NULL, it returns NULL.

Examples

Example 1: Single Character

To find the ASCII value of a single character ‘A’:

SELECT ASCII('A');
+------------+
| ASCII('A') |
+------------+
|         65 |
+------------+

The ASCII value of ‘A’ is 65.

Example 2: String Input

To get the ASCII value of the first character in a string ‘Hello’:

SELECT ASCII('Hello');
+----------------+
| ASCII('Hello') |
+----------------+
|             72 |
+----------------+

The ASCII value of ‘H’ is 72.

Example 3: Numeric Character

Finding the ASCII value of the character ‘4’:

SELECT ASCII('4');
+-------------+
| ASCII('4')  |
+-------------+
|          52 |
+-------------+

The ASCII value of ‘4’ is 52.

Example 4: Special Character

To find the ASCII value of the special character ‘#’:

SELECT ASCII('#');
+-------------+
| ASCII('#')  |
+-------------+
|          35 |
+-------------+

The ASCII value of ‘#’ is 35.

Example 5: Non-Printable Character

Calculating the ASCII value of the non-printable character ’newline’:

SELECT ASCII(CHAR(10));
+-----------------+
| ASCII(CHAR(10)) |
+-----------------+
|              10 |
+-----------------+

The ASCII value of the newline character is 10.

Here are a few functions related to the MariaDB ASCII() function:

  • MariaDB CHAR() function is used to convert an ASCII code back to a character.
  • MariaDB ORD() function is used to get the ASCII code of multi-byte characters.
  • MariaDB CHAR_LENGTH() function is used to return the number of characters in a string.

Conclusion

The ASCII() function is a simple yet powerful tool in MariaDB for converting characters to their corresponding ASCII values. It is especially useful when you need to perform operations based on the numeric representation of characters. As we’ve seen through various examples, ASCII() can handle different types of characters, including special and non-printable ones. Understanding its usage and related functions can enhance your ability to work with string data in MariaDB.