ApexSensei

Drills › Query the org (SOQL)

Filter Account names

Query the org (SOQL) · Beginner · 12 min · Runs in your Salesforce Developer org · Apex Path

Scenario. A territory helper needs Accounts whose names start with North, not names that only contain North somewhere.

Build a LIKE pattern that finds tagged Accounts whose names start with North, in any letter case, and skips close decoys.

What you will learn

WHERE keeps only rows that meet a condition. LIKE matches text patterns: % means any number of characters, and _ means exactly one character. LIKE ignores letter case, so North% also matches northbay.

String pattern = 'North%';
List<Account> rows = [SELECT Id FROM Account WHERE Name LIKE :pattern];

Gotcha. North% only matches names that start with North. %North% also matches North in the middle.

The task

Build a LIKE pattern and return only this run's Accounts whose names start with North.

Examples:

  • Northwind, Northstar and northbay → included, because LIKE ignores case → Filter count: 3
  • northbay is in the result → Filter lowercase included: true
  • Southwind and FarNorth (North is not at the start) → left out → Filter exclusions: true

Requirements:

  1. Build a String named northPattern from tag that matches names starting with tag + '-North'. End it with %.
  2. Query Account with WHERE Name LIKE :northPattern.
  3. Use the result Ids to check northbay (seeded[2]) and the two decoys (seeded[3] and seeded[4]).
  4. Print the count, whether northbay came back, and whether both decoys were left out. Print Filter count:, Filter lowercase included: and Filter exclusions:.

Starter code

String tag = 'AS-Q302-' + UserInfo.getUserId() + '-' +
    String.valueOf(Datetime.now().getTime());
List<Account> seeded = new List<Account>{
    new Account(Name = tag + '-Northwind'),
    new Account(Name = tag + '-Northstar'),
    new Account(Name = tag + '-northbay'),
    new Account(Name = tag + '-Southwind'),
    new Account(Name = tag + '-FarNorth')
};
insert seeded;

List<Account> matches = new List<Account>();
System.debug('Filter count: ' + matches.size());
System.debug('Filter lowercase included: false');
System.debug('Filter exclusions: false');

When it passes

The three North names come back in any letter case. Southwind and FarNorth are left out.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Query one Account · Rank practice Accounts ›