From c5acd10b3a8267b774937e66c830d26455b87e2e Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Wed, 21 Jul 2021 19:38:05 -0500 Subject: [PATCH] Add Two Ways To Escape A Quote In A String as a Postgres til --- README.md | 3 +- .../two-ways-to-escape-a-quote-in-a-string.md | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 postgres/two-ways-to-escape-a-quote-in-a-string.md diff --git a/README.md b/README.md index af51552..5b899b5 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1141 TILs and counting..._ +_1142 TILs and counting..._ --- @@ -630,6 +630,7 @@ _1141 TILs and counting..._ - [Truncate Tables With Dependents](postgres/truncate-tables-with-dependents.md) - [Turning Timing On](postgres/turn-timing-on.md) - [Two Ways To Compute Factorial](postgres/two-ways-to-compute-factorial.md) +- [Two Ways To Escape A Quote In A String](postgres/two-ways-to-escape-a-quote-in-a-string.md) - [Types By Category](postgres/types-by-category.md) - [Union All Rows Including Duplicates](postgres/union-all-rows-including-duplicates.md) - [Use A psqlrc File For Common Settings](postgres/use-a-psqlrc-file-for-common-settings.md) diff --git a/postgres/two-ways-to-escape-a-quote-in-a-string.md b/postgres/two-ways-to-escape-a-quote-in-a-string.md new file mode 100644 index 0000000..667181f --- /dev/null +++ b/postgres/two-ways-to-escape-a-quote-in-a-string.md @@ -0,0 +1,40 @@ +# Two Ways To Escape A Quote In A String + +String literals in PostgreSQL have to be wrapped in single quotes. This can be +tricky if you are faced with writing out a query using a string that contains a +single quote. + +```sql +> select 'who's on first?'; +... +``` + +The query won't execute because it is waiting for you to close the second set +of quotes. + +I know of two ways to handle this situation. + +The first is to put two single quotes back to back. The first will cause the +second to be escaped so that the quote shows up in the string. + +```sql +> select 'who''s on first?'; + ?column? +----------------- + who's on first? +(1 row) +``` + +The second is to prepend the string with [the `E` +character](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS) +to allow escape sequences in strings. + +```sql +> select E'who\'s on first?'; + ?column? +----------------- + who's on first? +(1 row) +``` + +[source](https://stackoverflow.com/a/12320729)