How the CHR() Function Works in PostgreSQL

In PostgreSQL, we can use the chr() function to return a character based on its code.

The code is provided as an integer argument, and the function returns the character that the code represents. When using UTF8 encoding the argument is treated as a Unicode code point, otherwise it must designate an ASCII character.

Example

Here’s an example to demonstrate:

SELECT chr(74);

Result:

J

In this case, 74 represents the J character and so that’s what’s returned.

Here are some more examples:

\x
SELECT 
    chr(80) AS "80",
    chr(81) AS "81",
    chr(82) AS "82",
    chr(83) AS "83",
    chr(84) AS "84";

Result (using vertical output):

80 | P
81 | Q
82 | R
83 | S
84 | T

Unicode Characters

As mentioned, when using UTF8 encoding the argument is treated as a Unicode code point. The following example illustrates this:

SELECT chr(246);

Result:

ö

Here, when 246 in decimal is converted to hexadecimal, we end up with F6, or U+00F6 in Unicode code point terms.

The same principle applies to the previous examples. For example, 74 in decimal is 4A in hexadecimal, or U+004A in Unicode code point terms.

Passing Zero

Passing zero returns an error:

SELECT chr(0);

Result:

ERROR:  null character not permitted

This is because text data types can’t store zero.

Passing null

Passing null returns null:

SELECT chr(null);

Result:

null