Explain Codes LogoExplain Codes Logo

How to Handle a Single Quote in Oracle SQL

sql
sql-injection
dynamic-sql
concatenation
Nikita BarsukovbyNikita Barsukov·Oct 19, 2024
TLDR

To escape a single quote in Oracle SQL, double it up, like so: 'O''Brien'. Doubling tells Oracle to treat the quote as a character, rather than a string delimiter.

SELECT 'It''s easy' FROM dual;

Running this query gets you It's easy, because the inner quote is seen as part of the text.

Alternate Quoting: The 10g+ Way

From Oracle version 10g and onwards, you can bypass the need to escape single quotes altogether by using a fancy method named q-quoting. This syntax lets you define your own string delimiter.

SELECT q'[It's simpler than you think]' FROM dual;

In this case, It's simpler than you think is returned. You're starting to see why this approach is preferred when dealing with lengthy strings containing an army of single quotes.

Dynamic SQL: Beware of Injections

When it comes to dynamic SQL, it's vital to watch out for SQL injection risk factors! A great way to handle single quotes safely is by using bind variables. Below is an illustration using PL/SQL:

BEGIN EXECUTE IMMEDIATE 'SELECT * FROM employees WHERE last_name = :1' USING 'O''Brien'; END;

This method not only keeps our single quote in check but also prevents SQL injection, since the string remains extern to the SQL statement's text. No dodgy injections here!

Concatenation and Manipulation: Handle with Care

Always fear concatenating strings that may be riddled with single quotes. Make wise use of concatenation functions or operators:

SELECT 'Name: ' || last_name FROM employees;

Even if last_name is O'Brien, this doesn't spit out an error, as you're not manually fiddling with the string's single quotes. A sigh of relief, isn't it?

Nuggets of Wisdom

  • The new quoting method isn't omnipresent: Confirm your Oracle version supports it.
  • Avoid hardcoding values with single quotes in your production code. Use bind variables or substitution variables whenever you can.
  • Testing - ever heard of it? Do some, especially on scripts that generate dynamic content, to make sure your escaping mechanisms are solid as a rock.