I have a table test(id,name)
.
I need to insert values like: user\'s log
, \'my user\'
, customer\'s
.
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'
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:
When dealing with values inside the database, there are a couple of useful functions to quote strings properly:
NULL
for null input. (There is also quote_ident() to double-quote strings where needed to get valid SQL identifiers.)%L
is equivalent to quote_nullable()
.format('%L', string_var)