Summary: In this tutorial, you’ll learn how to use the PostgreSQL function to return the ASCII code of the first character of a string.
Introduction to PostgreSQL ASCII function #
The ASCII
function returns the ASCII code of the first character of a string.
Here’s the syntax of the ASCII function:
ASCII(character_expression)
Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)
In this syntax:
character_expression
: A string (text or character type) from which you want to extract the ASCII code of the first character.
The ASCII
function returns an integer that represents the ASCII code of the first character of the input string. If the input
string is NULL
, the function returns NULL
.
ASCII Code of a Single Character #
The following example uses the ASCII
function to return the ASCII code of the character 'A'
:
SELECT
ASCII('A');
Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)
Output:
ascii
-------
65
Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)
The output shows that the ASCII code of the letter 'A'
is 65
.
Getting ASCII Code from a String #
The following query returns the ASCII code of the first character of the string ‘PostgreSQL’:
SELECT
ASCII('pgtutorial.com');
Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)
Output:
ascii
-------
112
Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)
The first character of "pgtutorial.com"
is 'p'
, which has an ASCII value of 112
.
Handling NULLs #
The following query returns NULL
because the input string is NULL
:
SELECT
ASCII(NULL);
Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)
Output:
ascii
-------
NULL
Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)
Summary #
- Use the
ASCII()
function to retrieve the ASCII value of the first character of a string.