ASCII Function - SQL


Overview


The ASCII function in SQL returns the ASCII code value of the leftmost character of a given string. It is useful for extracting the numeric ASCII code from a character, often for sorting or comparison purposes.

Example:

SELECT ASCII('A')

Syntax:

SELECT ASCII(character_expression)

character_expression is the string or character from which you want to get the ASCII code.

Sample Data:

department_id first_name
3 Frank
2 Jane
3 Ashley
NULL Glenn
2 Kelly
1 Richard
1 George
5 Kyle
2 James
1 Gustavo

Example: Hard-coded value


In this example, we are returning the ASCII code for the ‘A’ input, the output is 65.


Example: Query without the WHERE Statement


In this example, we are returning the ASCII code for the first letter of each name in the first_name column. You can see that the third result is 65 like in our earlier example because ‘Ashley’ starts with the letter ‘A’ and that is what the function is looking at.


Example: Query with the WHERE Statement


In this example, we are returning the ASCII code for the first letter of each name in the first_name column where the department_id equals 1. The first name on the list with a department_id of 1 is ‘Richard’ so the ASCII code for ‘R’ would be 82, which is what we see in the output.