function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Raj R.Raj R. 

How to query Contact name with apostrophe in soql?

Hi,

I have a situation where we have contact name's with characters such as an apostrophe in the Name field. What is the best way to still query the contact's name that contain an apostrophe?

Example scenario:
  • Contact.Name = "John D'oe";
  • Contact.Name = "John O'doe'
Current SOQL query:
//assume it is a single contact
String nm = contact.Name;

Select Id, Name From Contact Where Name =: nm;

The current error message: uncaught exception malformed query
Best Answer chosen by Raj R.
Vivek DVivek D
Hi,
Try using string method String.escapeSingleQuotes()
String contactName = String.escapeSingleQuotes(contact.Name);
Contact contact = [SELECT id,Name FROM Contact WHERE Name = :contactName];

 

All Answers

Vivek DVivek D
Hi,
Try using string method String.escapeSingleQuotes()
String contactName = String.escapeSingleQuotes(contact.Name);
Contact contact = [SELECT id,Name FROM Contact WHERE Name = :contactName];

 
This was selected as the best answer
Praveen KHariPraveen KHari
String LastName = 'John D\'oe';
system.debug('# LastName'+LastName);
List<Contact> ConList = [select ID, FirstName, LastName, Email From Contact Where LastName =:LastName]; 
system.debug('# Contact List '+ConList);