Skip to content

Apache DataFusion SQL Query Engine

Document SQL literal syntax and escaping (#14934)

Andrew Lambf9f256ca52e2
diff --git a/datafusion/sqllogictest/test_files/expr.slt b/datafusion/sqllogictest/test_files/expr.slt
index 7980b180ae..74e9fe065a 100644
--- a/datafusion/sqllogictest/test_files/expr.slt
+++ b/datafusion/sqllogictest/test_files/expr.slt
@@ -2057,3 +2057,16 @@ select 1 where null between null and 2;
query T
select 'A' where null between 2 and null;
----
+
+### Demonstrate use of E literals for escaping
+# should not have literal tab
+query T
+select 'foo\t\tbar';
+----
+foo\t\tbar
+
+# should have literal tab
+query T
+select E'foo\t\tbar';
+----
+foo bar
diff --git a/docs/source/user-guide/sql/operators.md b/docs/source/user-guide/sql/operators.md
index 51f1a26d0b..b63f552396 100644
--- a/docs/source/user-guide/sql/operators.md
+++ b/docs/source/user-guide/sql/operators.md
@@ -17,7 +17,7 @@
under the License.
-->
-# Operators
+# Operators and Literals
## Numerical Operators
@@ -552,3 +552,64 @@ Array Is Contained By
| true |
+-------------------------------------------------------------------------+
```
+
+## Literals
+
+Use single quotes for literal values. For example, the string `foo bar` is
+referred to using `'foo bar'`
+
+```sql
+select 'foo';
+```
+
+### Escaping
+
+Unlike many other languages, SQL literals do not by default support C-style escape
+sequences such as `\n` for newline. Instead all characters in a `'` string are treated
+literally.
+
+To escape `'` in SQL literals, use `''`:
+
+```sql
+> select 'it''s escaped';
++----------------------+
+| Utf8("it's escaped") |
++----------------------+
+| it's escaped |
++----------------------+
+1 row(s) fetched.
+```
+
+Strings such as `foo\nbar` mean `\` followed by `n` (not newline):
+
+```sql
+> select 'foo\nbar';
++------------------+
+| Utf8("foo\nbar") |
++------------------+
+| foo\nbar |
++------------------+
+1 row(s) fetched.
+Elapsed 0.005 seconds.
+```
+
+To add escaped characters such as newline or tab, instead of `\n` you use the
+`E` style strings. For example, to add the text with a newline
+
+```text
+foo
+bar
+```
+
+You can use `E'foo\nbar'`
+
+```sql
+> select E'foo\nbar';
++-----------------+
+| Utf8("foo
+bar") |
++-----------------+
+| foo
+bar |
++-----------------+
+```