pg_unescape_bytea — Unescape a string returned by an SQL query on a bytea (byte array) column, recovering the original binary string.


pg_unescape_bytea string


pg_unescape_bytea recovers a binary string from the escaped data returned by PostgreSQL when a bytea (byte array) column is queried. This command returns the original data from a bytea column which was inserted (for example) after being escaped with pg_escape_bytea. (An alternative to escaping and unescaping binary data is to use binary mode prepared queries. See pg_exec_prepared.)



The string to unescape. This should be the result of a query on a bytea column. Other uses are undefined (see notes).

Return Value

The unescaped binary data string. This is a regular Tcl string, which can contain arbitrary byte values.


This command uses or emulates the PostgreSQL libpq function PQunescapeBytea.

See also pg_escape_bytea. Note that pg_escape_bytea and pg_unescape_bytea are not inverses of each other. For example, a quote mark is translated to two quote marks by pg_escape_bytea, but pg_unescape_bytea does not change two quote marks back to a single quote mark. This asymmetry is due to the fact that SQL statements undergo an extra level of parsing with bytea columns. pg_escape_bytea prepares a string for both levels of parsing, but pg_unescape_bytea only has to undo one level of escaping.


The pgintcl implementation of this command is not an accurate emulation of the libpq function. This was done for performance reasons. Also, starting with PostgreSQL-9.0, the database supports two different encoding methods for bytea data when returned as text: hex mode and escape mode. This is controlled using a PostgreSQL configuration setting bytea_output which takes the values hex or escape. The default is hex mode. But Pgintcl-3.2.0 and earlier do not support hex mode encoding. Until this is fixed, you must set your database to use escape mode for bytea strings when using pgintcl.

When using escape mode encoding, pgintcl will return correct results for data that results from a query on a bytea column (that is, any data output by the byteaout backend function). Results are undefined for other uses. For example, give the two byte sequence \a (which will never be output by PostgreSQL for a bytea column), PQunescapeBytea will return the single character 'a', but pg_unescape_bytea will return the byte value 7 (because Tcl unescapes \a to ASCII bell).

This command was added in pgtclng-1.5.2 and in pgintcl-2.2.0.

See Section 5.10, “Example - Bytea Escaping - Picture Viewer, Part 2 - View Pictures” for an example. Logo

This version of the manual was produced for the Pgtcl-ng Sourceforge project web service site, which requires the logo on each page.

To download a logo-free copy of the manual, see the Pgtcl-ng project downloads area.