In MySQL, the ORD()
function returns the numeric value of the leftmost character of a given string. You provide the string as an argument.
If the leftmost character is a multibyte character, the returned value is calculated from the numeric values of its constituent bytes. If the leftmost character is not a multibyte character, the return value is its ASCII code (which is the same result as when using the ASCII()
function).
Syntax
The syntax goes like this:
ORD(str)
Where str
is the string from which you want the numeric code of the leftmost character.
Example 1 – Basic Usage
Here’s an example to demonstrate.
SELECT ORD('MySQL');
Result:
+----------------+ | ASCII('MySQL') | +----------------+ | 77 | +----------------+
So we can see that the numeric for the letter M is 77. This is exactly the same result we’d get if using the ASCII()
function, because the letter M falls within the ASCII range.
Here’s an example with the two functions side by side:
SELECT ASCII('M'), ORD('M');
Result:
+------------+----------+ | ASCII('M') | ORD('M') | +------------+----------+ | 77 | 77 | +------------+----------+
Example 2 – Multibyte Characters
Here’s an example that uses multibyte characters.
SELECT ORD('€'), ORD('á'), ORD('仮'), ORD('平'), ORD('✓');
Result:
+------------+-----------+------------+------------+------------+ | ORD('€') | ORD('á') | ORD('仮') | ORD('平') | ORD('✓') | +------------+-----------+------------+------------+------------+ | 14844588 | 50081 | 14990254 | 15055283 | 14851219 | +------------+-----------+------------+------------+------------+
Example 2 – Case Sensitivity
Uppercase characters have a different numeric value to their lowercase counterparts. Example:
SELECT ORD('A'), ORD('a');
Result:
+----------+----------+ | ORD('A') | ORD('a') | +----------+----------+ | 65 | 97 | +----------+----------+