· Jul 20, 2022

Dealing with single Quote in SQL Query

Hi Guys 

how do I deal with single Quote inside string in an SQL query?

currently this type of query is failing with an error asking me for a closing quote :

Select * from cnd.Facilities  where name like ''%Grill's BBQ%'


Product version: Caché 2014.1
Discussion (5)1
Log in or sign up to continue

There's two ways around this:

  1. If this is something you're running one off in, say, the sql query tool within the management portal, then you will want to repeat the single quote to be "Select * from cnd.Facilities  where name like ''%Grill''s BBQ%'" and this will escape the single quote.
  2. If this is a query being called within your code and the value could be anything passed to it, then you will want to look to use parameterised SQL queries. An example can be found for SQL adapters here.

The issue of no results being returned is likely elsewhere in your query.

To test this, I created a basic table with the following:

    Name varchar(100),
    Type varchar(50),
    isActive bit

And I then added a few rows:

Insert into Demo.BBQ (Name, Type, isActive)
VALUES('Super Grill''s BBQ Hut','Outdoor',1)
Insert into Demo.BBQ (Name, Type, isActive)
VALUES('Bobs BBQ Bistro','Indoor',1)
Insert into Demo.BBQ (Name, Type, isActive)
VALUES('Rubbish Grill''s BBQ Resort','Not Known',0)

This then gave me a table that looks like this (note that the double single quotes used in the insert are inserted as a single quotes into the table):

If I then run a query using the like function:

And if I want to exclude the inactive location:

The use of doubling up a single quote to escape the character is not a Intersystems specific approach, but is generally a standard SQL way of escaping the single quote.