I faced an issue when tried to insert apostrophe word into the table, seeing the issue I become panic, how would I resolve this issue, so I did google surfing and found a lot of solutions, and I want to share it with you.
To create the scenario I will create a table to execute the following PostgreSQL statement.
CREATETABLEbooks ( idintgeneratedalwaysasidentity, titletext ); |
Now, I will try to insert the single quote value into the Title column, let's see what output comes.
INSERTINTObooks(title)VALUES('No Man'sLand'); |
Output:
ERROR: syntax error at or near "s"
LINE 3: INSERT INTO books (title) VALUES ('No Man's Land');
Some queries are given below please try it.
Replace a single quote (apostrophe) with double-quotes.
INSERTINTObooks(title)VALUES('No Man''s Land'); --select query on books SELECTtitleFROMbooksLIMIT 1; |
Propend your string with E to declare Posix escape string syntax, and you can also escape with the backslash \
INSERTINTObooks(title)VALUES (E'No Man\'sLand'); --select query on books SELECTtitleFROMbooksLIMIT 1; |
If we are using \ to resolve the issue, it may create an issue if we have to insert \ into the table. The following query may help you.
To further, avoid confusion among dollar-quotes, add a unique token to each pair.
INSERTINTObooks(title)VALUES ($$NoMan's Land$$); --select query on books SELECTtitleFROMbooksLIMIT 1; |