I have a table test(id,name)
.
I need to insert values like: user\'s log
, \'my user\'
, customer\'s
.
If you need to get the work done inside Pg:
to_json(value)
https://www.postgresql.org/docs/9.3/static/functions-json.html#FUNCTIONS-JSON-TABLE
In postgresql if you want to insert values with '
in it then for this you have to give extra '
insert into test values (1,'user''s log');
insert into test values (2,'''my users''');
insert into test values (3,'customer''s');
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.
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)
you can use the postrgesql chr(int) function:
insert into test values (2,'|| chr(39)||'my users'||chr(39)||');
select concat('''','abc','''')