Lesson

MySQL ASCII() Function

10 min reading
Free Course

MySQL ASCII() Function

The ASCII() function returns the numeric code value of the leftmost byte in a string. Developers use it to inspect character encodings, detect non-ASCII input, and validate SKU prefixes.

Syntax

ASCII(str)
  • str: Any string expression or value that MySQL can convert to a string.
  • Return value: An integer from 0 to 255 representing the first byte of str.

When you pass a number such as 9, MySQL converts it to '9' first and returns 57.

Practical Example

Suppose your catalog team stores product codes in demo_products. You want to verify that every sku starts with an uppercase ASCII letter (65 to 90) and flag unexpected symbols.

SELECT
    product_id,
    sku,
    product_name,
    ASCII(sku) AS first_byte_code
FROM demo_products
ORDER BY product_id;
product_id sku product_name first_byte_code
1 A104-USB USB-C Hub 65
2 B209-KEY Mechanical Keyboard 66
3 900-CASE Laptop Sleeve 57
4 €50-GIFT Gift Voucher 226
5 NULL Draft Item NULL

Row 3 starts with '9', whose ASCII code is 57. Row 4 starts with '€', a three-byte UTF-8 character whose leading byte is 226.

Common Mistakes & NULL Behavior

  • Multibyte UTF-8 characters: ASCII() reads only the first byte, not the full Unicode code point. Use ORD() if you need the full multibyte numeric code.
  • Empty strings vs. NULL: ASCII('') returns 0, while ASCII(NULL) returns NULL. Do not treat 0 and NULL as identical in WHERE filters.
  • Whitespace surprises: A leading space returns 32, which hides behind normal-looking text. Trim input with LTRIM() before checking prefix codes.

Frequently Asked Questions

Does MySQL ASCII() work on integer columns?

Yes. MySQL implicitly casts numbers to strings before reading the leftmost byte, so ASCII(25) returns 50 (the code for '2').

What is the difference between ASCII() and ORD()?

ASCII() always inspects one byte. ORD() detects multibyte UTF-8 sequences and calculates a combined numeric code for characters outside the 0–127 ASCII range.

How do I convert an ASCII code back into a character?

Use CHAR(code USING utf8mb4). For example, CHAR(65 USING ascii) returns 'A'.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum