Bind an Account name
Query the org (SOQL) · Beginner · 12 min · Runs in your Salesforce Developer org · Apex Path
Scenario. A search helper gets an Account name that may contain an apostrophe. It must not build query text from that name.
Bind Apex String values into SOQL, including a name with an apostrophe and a name that matches nothing.
What you will learn
A bind variable puts an Apex value into SOQL with :variable. Salesforce handles quotes for you, so a name like O'Brien just works.
String wanted = 'Acme';
List<Account> rows = [SELECT Id FROM Account WHERE Name = :wanted];
Gotcha. Never build query text by adding user input to a String and passing it to Database.query.
The task
Find an Account whose name has an apostrophe, then show that a name with no match returns zero rows, using bind variables for both.
Examples:
- a bound name ending
O'Brien→Bind found: 1andBind quote safe: true - a bound name that no Account has →
Bind missing: 0 - the Decoy Account → not returned →
Bind decoy excluded: true
Requirements:
- Query Account with
WHERE Name = :wantedName. - Make a second variable for a name that doesn't exist, such as
tag + '-Missing', and bind it in a second query. - Set
foundCountandmissingCountfrom the two results. They start at -1, so an empty result can't pass by accident. - Print both counts, whether the found Name equals
wantedName, and whether the decoy was left out. PrintBind found:,Bind quote safe:,Bind missing:andBind decoy excluded:.
Starter code
String tag = 'AS-Q304-' + UserInfo.getUserId() + '-' +
String.valueOf(Datetime.now().getTime());
String wantedName = tag + '-O\'Brien';
List<Account> seeded = new List<Account>{
new Account(Name = wantedName),
new Account(Name = tag + '-Decoy')
};
insert seeded;
Integer foundCount = -1;
Integer missingCount = -1;
System.debug('Bind found: ' + foundCount);
System.debug('Bind quote safe: false');
System.debug('Bind missing: ' + missingCount);
System.debug('Bind decoy excluded: false');
When it passes
The O'Brien Account is found once, the missing name returns zero rows, and the decoy is not returned.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.