MySQL ASCII() Function – How to find ASCII values in MySQL?

Mysql Ascii Function

In this tutorial, we will learn about the MySQL ASCII() function. The American Standard Code for Information Interchange, or ASCII, is a character encoding standard for electronic communication. Since computers can only understand numbers, the ASCII numeric codes are used to represent text in computers. You may read more about ASCII over here.

The MySQL ASCII() function is one of the many string functions in MySQL. It is used to return the ASCII value of the leftmost character in a given string. Knowing ASCII values can be very useful in encoding and decoding operations. 


Syntax of MySQL ASCII()

ASCII(character);Code language: SQL (Structured Query Language) (sql)

Where, character – It contains the character whose ASCII value is to be found out. If multiple characters are mentioned, then the ASCII value of the leftmost character is returned.


Examples of MySQL ASCII()

Let’s look at some of the examples of the ASCII function to understand the usage in better detail.

Basic Examples of MySQL ASCII()

Let us find the ASCII of a few characters like – ‘A’, ‘r’, ‘8’ and ‘#’. We will use the SELECT statement.

SELECT ASCII(‘A’);
SELECT ASCII(‘r’);
SELECT ASCII(‘8’);
SELECT ASCII(‘#’);Code language: SQL (Structured Query Language) (sql)

And we get the output as follows,

Ascii Simple Example

You may refer to the ASCII table on this link to verify the result.

Using ASCII() with tables

Consider the below Employee table.

Union Employee Table
Employee Table

ASCII of Numeric Values

Let us find the ASCII value of all the eid column values.

SELECT ASCII(eid) FROM Employee;Code language: SQL (Structured Query Language) (sql)

And you get the output as,

Ascii Numeric Example

Wait, why is the ASCII of 10 and 1 the same? That is because the ASCII() function considers only the leftmost character if more than one character is mentioned. So for the last eid, instead of considering ‘10’ as the character, the function considered ‘1’ as the character.

ASCII of Alphabetic Values

Let us find the ASCII values of the ‘PUN’ office code value. Since ASCII considers only the leftmost character if multiple characters are mentioned, we will get the ASCII value of ‘P’ as our result. We will add the DISTINCT keyword so that we don’t get a repeat value in our result-set. Our query with the WHERE clause is,

SELECT DISTINCT ASCII(Office_Code) FROM Employee WHERE Office_Code=’PUN’;Code language: SQL (Structured Query Language) (sql)

And, our output is,

Ascii Alphabet Example

Conclusion

MySQL ASCII() is a part of the powerful string functions of MySQL. Knowing and mastering string functions of MySQL is an important step towards mastering databases. I encourage you to explore the references.


References