pg_escape_string — Escape a string for use in an SQL string constant


pg_escape_string ?conn? string


pg_escape_string returns its argument with added characters which makes it safe for use in single-quoted SQL string constants. It returns the string with all single quote marks doubled, and in some cases doubles backslash characters too.

For example, pg_escape_string {can't} returns the string can''t.



Optional handle of the connection that the string should be escaped for sending to.


The string to escape.

Return Value

The string argument, with added characters.


See also pg_quote, pg_escape_literal, and pg_escape_identifier.

The optional conn argument was added to this command in pgtclng-1.7.0 and in pgintcl-3.1.0.

The conn argument is used to get character set encoding information, and the state of the PostgreSQL server configuration parameter standard_conforming_strings. The character set encoding is used to make sure that multi-byte characters do not confuse the escaping process. The state of the standard conforming strings setting is used to determine if backslashes need to be doubled. If the conn parameter is supplied, these settings can be accurately determined for the specific database connection being used. (Note that this information is maintained on the client side and does not necessitate any additional database server traffic.)

If the conn parameter is not supplied, a best guess will be made based on the most recent information from any database connection by the client. Therefore, if the client makes a single database connection, or multiple connections with the same encoding and setting for standard_conforming_strings, there is no need to provide the conn parameter.


Pgintcl uses the conn parameter only to determine if standard_conforming_strings is on. Unlike libpq-based interface implementations, it does not have the ability to use character set encoding information.

This command uses or emulates the PostgreSQL libpq function PQescapeString, if no connection handle is supplied, or PQescapeStringConn if a connection handle is supplied.


The Pgtcl implementation at (previously at has a command with the same name, but incompatible behavior. Their pg_escape_string works like pg_quote, and returns quotes around the result. In the Pgtcl-ng and Pgintcl implementations, pg_escape_string matches the libpq PQescapeString() function behavior, which returns the escaped value without single quotes.


set sql "SELECT * FROM mytable WHERE name = '[pg_escape_string $itemname]'" 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.