Summary: in this tutorial, you will learn how to use the MySQL ASCII()
function to get the ASCII
code of a character.
Introduction to MySQL ASCII function
ASCII stands for American Standard Code for Information Interchange. It is a character encoding standard representing text and control characters using numeric values.
Since ASCII uses 7-bit binary code to represent characters, it can have 128 characters. In ASCII, each character is assigned a unique number ranging from 0 to 127. For example, the decimal value for the letter ‘A’ is 65.
In MySQL, the ASCII function returns a number value of the first character of a string. The following shows the syntax of the ASCII function:
ASCII(string)
Code language: SQL (Structured Query Language) (sql)
In this syntax, the string is the character or string for which you want to find the ASCII
value. If the string is null, the ASCII returns NULL
.
MySQL ASCII function examples
Let’s take some examples of using the ASCII()
function.
1) Getting ASCII of a single character
The following example uses the ASCII()
function to get the ASCII code of the character ‘A’:
SELECT ASCII('A');
Code language: SQL (Structured Query Language) (sql)
Output:
+------------+
| ASCII('A') |
+------------+
| 65 |
+------------+
1 row in set (0.00 sec)
Code language: SQL (Structured Query Language) (sql)
The ASCII
code of the letter ‘A’ is 65.
2) Getting ASCII of the leftmost character of a string
If you pass a string that contains multiple characters, the ASCII()
function will return the ASCII code of the leftmost character for example:
SELECT
ASCII('MySQL');
Code language: SQL (Structured Query Language) (sql)
Output:
+----------------+
| ASCII('MySQL') |
+----------------+
| 77 |
+----------------+
1 row in set (0.00 sec)
Code language: SQL (Structured Query Language) (sql)
In this example, the ASCII
function returns the ASCII code of the letter M in the string MySQL.
3) Using the ASCII function with table data
We’ll use the products
table in the sample database for the demonstration:
The following example uses the ASCII
function to find the products whose names have the first character with the ASCII
code greater than 66:
SELECT
productName
FROM
products
WHERE
ASCII(productName) > 66;
Code language: SQL (Structured Query Language) (sql)
Output:
+----------------------------------+
| productName |
+----------------------------------+
| P-51-D Mustang |
| Collectable Wooden Train |
| Corsair F4U ( Bird Cage) |
| Diamond T620 Semi-Skirted Tanker |
| The Schooner Bluenose |
| The Mayflower |
| HMS Bounty |
| The USS Constitution Ship |
| F/A 18 Hornet 1/72 |
| The Titanic |
| The Queen Mary |
| Pont Yacht |
+----------------------------------+
12 rows in set (0.02 sec)
Code language: SQL (Structured Query Language) (sql)
Summary
- Use the MySQL
ASCII
() function to find theASCII
code of the leftmost character of a string.