How to Return the ASCII Code Value for a given Character in SQL Server

If you ever need to find the ASCII code for a given character when using SQL Server, the T-SQL ASCII() function is probably what you need.

The ASCII() function returns the ASCII code value of the leftmost character of a character expression. Simply provide the character as an argument and SQL Server will return the ASCII value of that character (or the leftmost character in the string).

Syntax

The syntax goes like this:

ASCII ( character_expression )

Where character_expression is an expression of type char or varchar.

Example

As an example, here’s how you’d find out the ASCII value of the letter A:

SELECT ASCII('A');

Result:

65

So by this example, we can see that the letter A has an ASCII value code of 65.

Case-Sensitivity

Note that uppercase and lowercase characters have different ASCII values. So if we use a lowercase a we get a different value:

SELECT ASCII('a');

Result:

97

Leftmost Character Only

Also note that the ASCII() function only returns the ASCII value for the leftmost character:

SELECT ASCII('Aa');

Result:

65

Unicode Characters

If you have characters that fall outside the ASCII range, you can use the UNICODE() function to return the Unicode value instead. This function will also work on ASCII characters, given that the first 128 Unicode code points are dedicated to the ASCII values.