Insert text with single quotes in PostgreSQL
According to PostgreSQL documentation (4.1.2.1. String Constants):
To include a single-quote character within a string constant, write two adjacent single quotes, e.g. 'Dianne''s horse'.
See also the standard_conforming_strings
parameter, which controls whether escaping with backslashes works.
String literals
Escaping single quotes '
by doubling them up → ''
is the standard way and works of course:
'user's log' -- incorrect syntax (unbalanced quote)
'user''s log'
Plain single quotes (ASCII / UTF-8 code 39), mind you, not backticks `
, which have no special purpose in Postgres (unlike certain other RDBMS) and not double-quotes "
, used for identifiers.
In old versions or if you still run with standard_conforming_strings = off
or, generally, if you prepend your string with E
to declare Posix escape string syntax, you can also escape with the backslash \
:
E'user\'s log'
Backslash itself is escaped with another backslash. But that's generally not preferable.
If you have to deal with many single quotes or multiple layers of escaping, you can avoid quoting hell in PostgreSQL with dollar-quoted strings:
'escape '' with '''''
$$escape ' with ''$$
To further avoid confusion among dollar-quotes, add a unique token to each pair:
$token$escape ' with ''$token$
Which can be nested any number of levels:
$token2$Inner string: $token1$escape ' with ''$token1$ is nested$token2$
Pay attention if the $
character should have special meaning in your client software. You may have to escape it in addition. This is not the case with standard PostgreSQL clients like psql or pgAdmin.
That is all very useful for writing plpgsql functions or ad-hoc SQL commands. It cannot alleviate the need to use prepared statements or some other method to safeguard against SQL injection in your application when user input is possible, though. @Craig's answer has more on that. More details:
- SQL injection in Postgres functions vs prepared queries
Values inside Postgres
When dealing with values inside the database, there are a couple of useful functions to quote strings properly:
quote_literal()
orquote_nullable()
- the latter outputs the stringNULL
for null input.
There is alsoquote_ident()
to double-quote strings where needed to get valid SQL identifiers.format()
with the format specifier%L
is equivalent toquote_nullable()
.
Like:format('%L', string_var)
orconcat()
are typically no good for this purpose as those do not escape nested single quotes and backslashes.concat_ws()