Skip navigation.

How does one escape special characters when writing SQL queries?

Escape quotes

Use two quotes for every one displayed. Examples:

SQL> SELECT 'Frank''s Oracle site' AS text FROM DUAL;

Franks's Oracle site

SQL> SELECT 'A ''quoted'' word.' AS text FROM DUAL;

A 'quoted' word.

SQL> SELECT 'A ''''double quoted'''' word.' AS text FROM DUAL;

A ''double quoted'' word.

Escape wildcard characters

The LIKE keyword allows for string searches. The '_' wild card character is used to match exactly one character, while '%' is used to match zero or more occurrences of any characters. These characters can be escaped in SQL. Examples:

SELECT name FROM emp 
   WHERE id LIKE '%/_%' ESCAPE '/';

SELECT name FROM emp 
   WHERE id LIKE '%\%%' ESCAPE '\';

Escape ampersand (&) characters in SQL*Plus

When using SQL*Plus, the DEFINE setting can be changed to allow &'s (ampersands) to be used in text:

SELECT 'Lorel & Hardy' FROM dual;

Other methods:

Define an escape character:

SELECT '\&abc' FROM dual;

Don't scan for substitution variables:

SELECT '&ABC' x FROM dual;

User defined quoted characters is supported in Oracle10g

Oracle10g allows you to define your own string delimiters. Any character that is not present in the string can be defined as:

--Previous syntax
dbms_output.put_line('Hi Ram''s!');

--New syntax
dbms_output.put_line(q'#Hi Ram's!#');
dbms_output.put_line(q'$Hi Ram's!$');

What about dynamic SQL?

When passing string values from a user interface into an Oracle stored procedure, for use in a dynamicly constructed SQL query, they must be "escaped" to insure the query isn't broken or worse, provide a security whole.

Your examples don't cover this situation, nor how to escape characters in a simple where clause such as:

select * from employee where last_name = vUiInputValueVariable;

Without an escape, a string such as '%';delete from employee
could wipe out the table!

Of course writting dynamic SQL such as this is very bad practice, but its possible if the input string is properly escaped.

One online Oracle documentation source for version 9.2( indicates braces ( {} ) or a backslash ( \ ) can be used to escape entire strings or characters. However those techniques do not work for some reason on our Oracle 9.2 installation.

I hope this info is helpful.