In MySQL, you can use the ASCII() function to return the ASCII code for a given character. More specifically, it returns the ASCII code for the leftmost character in a given string.
You can also use ORD(), which works the same way, except that it also supports multibyte characters.
Syntax
Here’s the syntax for the ASCII() function:
ASCII(str)
Where str is the string that you want the ASCII code of the leftmost character from.
Example
Here’s an example:
SELECT ASCII('Z');
Result:
+------------+
| ASCII('Z') |
+------------+
| 90 |
+------------+
So we can see from this example that the uppercase letter Z has an ASCII code of 90.
Note that there’s a different ASCII code for uppercase letters vs lowercase. So to get the ASCII code for the lowercase z, we’d need to provide the lowercase z as the argument:
SELECT ASCII('z');
Result:
+------------+
| ASCII('z') |
+------------+
| 122 |
+------------+
And as mentioned, only the leftmost character is returned:
SELECT ASCII('Zz');
Result:
+-------------+
| ASCII('Zz') |
+-------------+
| 90 |
+-------------+
An Alternative: The ORD() Function
You can also use the ORD() function to return the ASCII value of a character.
SELECT ORD('Z');
Result:
+----------+
| ORD('Z') |
+----------+
| 90 |
+----------+
The difference between ASCII() and ORD() is that, ORD() can also return values for multibyte characters whereas ASCII() is limited to just the ASCII range.