In MySQL, the ASCII() function returns the numeric ASCII code of the leftmost character of a given string. You provide the string as an argument.
This article contains examples of usage.
Syntax
The syntax goes like this:
ASCII(str)
Where str is the string that you want the ASCII code of the leftmost character from.
Example 1 – Basic Usage
Here’s an example to demonstrate.
SELECT ASCII('MySQL');
Result:
+----------------+
| ASCII('MySQL') |
+----------------+
| 77 |
+----------------+
So we can see that the ASCII code for the letter M is 77.
To be absolutely clear, let’s get the ASCII code for each letter:
SELECT
ASCII('M'),
ASCII('y'),
ASCII('S'),
ASCII('Q'),
ASCII('L');
Result:
+------------+------------+------------+------------+------------+
| ASCII('M') | ASCII('y') | ASCII('S') | ASCII('Q') | ASCII('L') |
+------------+------------+------------+------------+------------+
| 77 | 121 | 83 | 81 | 76 |
+------------+------------+------------+------------+------------+
Example 2 – Case Sensitivity
Uppercase characters have a different ASCII code to their lowercase counterparts. Example:
SELECT
ASCII('m'),
ASCII('M');
Result:
+------------+------------+
| ASCII('m') | ASCII('M') |
+------------+------------+
| 109 | 77 |
+------------+------------+
Example 3 – A Database Example
Here’s an example of using the ASCII() function in a database query.
USE Music; SELECT AlbumName, ASCII(AlbumName) AS 'ASCII code of leftmost character' FROM Albums LIMIT 10;
Result:
+-------------------------+----------------------------------+ | AlbumName | ASCII code of leftmost character | +-------------------------+----------------------------------+ | Powerslave | 80 | | Powerage | 80 | | Singing Down the Lane | 83 | | Ziltoid the Omniscient | 90 | | Casualties of Cool | 67 | | Epicloud | 69 | | Somewhere in Time | 83 | | Piece of Mind | 80 | | Killers | 75 | | No Prayer for the Dying | 78 | +-------------------------+----------------------------------+
Example 4 – Rightmost Character
In this example I return the ASCII code of the rightmost character.
USE Music; SELECT AlbumName, RIGHT(AlbumName, 1) 'Rightmost character', ASCII(RIGHT(AlbumName, 1)) 'ASCII code' FROM Albums LIMIT 10;
Result:
+-------------------------+---------------------+------------+ | AlbumName | Rightmost character | ASCII code | +-------------------------+---------------------+------------+ | Powerslave | e | 101 | | Powerage | e | 101 | | Singing Down the Lane | e | 101 | | Ziltoid the Omniscient | t | 116 | | Casualties of Cool | l | 108 | | Epicloud | d | 100 | | Somewhere in Time | e | 101 | | Piece of Mind | d | 100 | | Killers | s | 115 | | No Prayer for the Dying | g | 103 | +-------------------------+---------------------+------------+