ASCII( )

This MySQL function returns the numeric code corresponding to the first character of a given string.

Syntax

Below is the syntax for this command. Text within square brackets (i.e, [ and ] ) are optional. Choices are separated by bars (i.e, | ). Ellipses preceded by a comma indicates a repeating pattern. Ellipses before or after syntax are used to highlight a relevant except from the larger syntax. Text displayed in italic letters represent text that should be replaced with the specific names related to the database (e.g., column with the name of the column).

ASCII(string)

Explanation

This function returns the numeric code corresponding to the first character of a given string. If the given string is empty, 0 is returned. Despite the fuction's name, it works for characters outside the ASCII set (that is, characters that correspond to values above 127) and is probably most useful for such characters.

Examples

As an example of this function's use, suppose that for a college we had a table listing the names of fraternities with their Greek letters. For easier manipulation of the data contained in a column, we might want to convert the Greek letters to a numeric code with this function:

SELECT greek_id,
CONCAT_WS('-',
   ASCII( SUBSTR(greek_id, 1, 1) ),
   ASCII( SUBSTR(greek_id, 2, 1) ),
   ASCII( SUBSTR(greek_id, 3, 1) )
) AS 'ASCII Values'
FROM fraternities WHERE frat_id = 101;

+----------+--------------+
| greek_id | ASCII Values |
+----------+--------------+
| ΔΣΠ      | 196-211-208  |
+----------+--------------+

In this example, we use the SUBSTR( ) function to extract each letter so we can then convert each one individually to its numeric equivalent with the ASCII( ) function. Then, using the CONCAT_WS( ), we insert hyphens between each number returned. We can use this number to more easily manage the data related to this fraternity. See the descriptions of CHAR( ) and CONVERT( ) for more information on this function and for more details related to this example.