ApexSensei

Drills › Query the org (SOQL)

Rank practice Accounts

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

Scenario. A review screen needs a stable preview of two Accounts, not a random pair.

Sort four tagged Account names descending and keep only the first two records.

What you will learn

ORDER BY sets the order of the results, and LIMIT caps how many rows come back.

SELECT Id, Name FROM Account ORDER BY Name DESC LIMIT 2

Gotcha. LIMIT without ORDER BY gives you some rows, but Salesforce doesn't promise which ones.

The task

Sort this run's four Accounts by Name from Z to A, and keep only the top two.

Examples:

  • names ending A, B, C, D sorted descending → D, C, B, A
  • LIMIT 2 → Top count: 2, with D first (Top first: true) and C second (Top second: true)
  • B is the next row after the cut → Top B left out: true

Requirements:

  1. Filter to this run's Accounts with Name LIKE :tagPrefix.
  2. Sort by Name descending.
  3. Limit the result to two rows.
  4. Print the count, true/false for D first and C second, and whether B was left out. Print Top count:, Top first:, Top second: and Top B left out:.

Starter code

String tag = 'AS-Q303-' + UserInfo.getUserId() + '-' +
    String.valueOf(Datetime.now().getTime());
String tagPrefix = tag + '%';
List<Account> seeded = new List<Account>{
    new Account(Name = tag + '-A'),
    new Account(Name = tag + '-B'),
    new Account(Name = tag + '-C'),
    new Account(Name = tag + '-D')
};
insert seeded;

List<Account> topRows = new List<Account>();
System.debug('Top count: ' + topRows.size());
System.debug('Top first: false');
System.debug('Top second: false');
System.debug('Top B left out: false');

When it passes

The query returns D then C, stops at two rows, and leaves B out.

Try this drill free

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

‹ Filter Account names · Bind an Account name ›