Full answer
Tables and rows used here:
sql
CREATE TABLE notes (id int, body text);
INSERT INTO notes VALUES (1, 'It''s done'), (2, E'line1\nline2'), (3, $$C:\path 'quoted'$$);sql
SELECT id, body, length(body) AS len FROM notes ORDER BY id;Result on PostgreSQL 17:
text
id | body | len
----+------------------+-----
1 | It's done | 9
2 | line1
line2 | 11
3 | C:\path 'quoted' | 16
(3 rows)sql
SELECT 'a\nb' AS standard, length('a\nb') AS standard_len, length(E'a\nb') AS escape_len, $tag$has $$ inside$tag$ AS tagged;Result:
text
standard | standard_len | escape_len | tagged
----------+--------------+------------+---------------
a\nb | 4 | 3 | has $$ inside
(1 row)The doubled quote stores "It's done". The E-string turns \n into a real newline, so its value spans two lines in the output. The dollar-quoted value keeps the backslash and the quotes exactly as written. In a standard string, 'a\nb' is four characters including a literal backslash, while E'a\nb' is three. A tag such as $tag$ allows $$ inside the text. Application code should not build SQL strings by hand at all; driver parameters handle quoting safely.
sql
CREATE TABLE notes (id int, body text);
INSERT INTO notes VALUES (1, 'It''s done'), (2, E'line1\nline2'), (3, $$C:\path 'quoted'$$);
SELECT id, body, length(body) AS len FROM notes ORDER BY id;
SELECT 'a\nb' AS standard, length('a\nb') AS standard_len, length(E'a\nb') AS escape_len, $tag$has $$ inside$tag$ AS tagged;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- Double single quotes in standard strings
- Backslashes are literal by default
- E'' enables escapes
- Dollar quoting needs no escaping
- Use parameters in application code
Common mistakes
- Escaping quotes with backslashes in standard strings
- Building SQL with string concatenation
Follow-ups
- What does quote_literal do?
- Why are function bodies dollar-quoted?
Tips
- Show the length difference