PostgreSQL ASCII Function

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)

Try it

Output:

 ascii
-------
    65Code 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)

Try it

Output:

 ascii
-------
   112Code 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)

Try it

Output:

 ascii
-------
  NULLCode 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.
Was this tutorial helpful ?