Escaping ampersand character in SQL string
To escape an ampersand (&
) in SQL quickly, use two ampersands in sequence (&&
), or concatenate with the CHR
function and 38
—the ASCII code for &
.
With double ampersands:
Using CHR
function:
SQL*Plus: Don't ask, just do!
In Oracle's SQL*Plus, ampersands are substitution variables by default, and might ask for your input when you least expect it! To avoid this, run:
This lets the ampersand chill and behave like a normal character in your strings.
Wildcard party with LIKE operator
Searching for patterns that include an ampersand? Use the LIKE
operator and the "wild child", underscore _
, as a single-character wildcard:
This fetches names that start with 'A', hold any amped-up character followed by '_Smith'.
The secret handshake: String concatenation using ||
If complex string construction is your jam, use the ||
, the secret handshake for string concatenation, and usher in ampersands as needed:
Oracle nuance central: Backslashes & Escape mechanisms
Backslashes (\
) may seem like a good idea, but Oracle SQL thinks differently. Try set define off
or set escape on
instead:
Quick-fire tips & tricks
Know thy environment
SQL context matters. set define off
works in SQL*Plus, but not other tools like SQL Developer. Check your Preferences
in these cases.
Test, test, and test again
Validate your SQL syntax after applying escape sequences. It's like your code's final health check before it goes out into the world.
PL/SQL considerations
Working with dynamic SQL or PL/SQL? Be vigilant about quoting string literals properly to fend off errors or SQL injection.
Read, re-read your database docs
Each database has its special escape mechanisms. It's important to refer to the relevant documentation like a developer's version of encyclopedia!
Was this article helpful?