MySQL ASCII() Function

The ASCII() function in MySQL is used to retrieve the ASCII value of a specified character. ASCII values are numeric representations of characters based on the ASCII (American Standard Code for Information Interchange) standard. This function is particularly useful when working with character encoding or comparing characters in a database.


Syntax

ASCII(character)

Parameters

Parameter Description
character Required. The character to retrieve the ASCII value for. If multiple characters are provided, only the first character's ASCII value will be returned.

Usage Example

To retrieve the ASCII value of the first character in the CustomerName column of the Customers table, use the following SQL query:

SELECT ASCII(CustomerName) AS NumCodeOfFirstChar
FROM Customers;

Output Explanation:

  • For a CustomerName value like "John", the function will return 74 because J is the first character and its ASCII value is 74.

Definition and Use

  • Purpose: The ASCII() function is used to find the numeric ASCII value of a given character.
  • Behavior: If the input is a string, only the ASCII value of the first character is returned.

Technical Details

  • Availability: The ASCII() function is available starting from MySQL 4.0.
  • Return Type: Returns an integer representing the ASCII value.

Practical Use Cases

  1. Data Validation: Verify that certain characters in a string meet specific ASCII criteria (e.g., alphabetical range).
  2. Sorting and Ranking: Compare strings based on ASCII values of characters.
  3. Data Transformation: Map ASCII values to characters in applications requiring encoded or custom data representations.

Example Outputs

Suppose the Customers table contains the following values:

CustomerName
Alice
Bob
Charlie

After running the query:

SELECT ASCII(CustomerName) AS NumCodeOfFirstChar
FROM Customers;

The result will be:

NumCodeOfFirstChar
65
66
67

By using the ASCII() function, you can efficiently perform operations that rely on character encoding, enabling greater flexibility in handling textual data in MySQL databases.


Was this article helpful?