SOQL & SOSL

Easy SOQL & SOSL Practice Problems

38 free Salesforce Apex challenges · Full problem statements, best-practice notes, and step-by-step hints · Solve live on ApexArena

This guide walks through 38 foundational SOQL queries — filtering, ordering, and basic relationship queries. Each entry below includes the full problem statement, the governor-limit and best-practice constraints it's testing, and a numbered approach to solving it — then you can open the same problem in ApexArena's browser-based Apex editor and get instant pass/fail feedback against real test cases.

On this page
  1. 1. SOQL Aggregate Rollup
  2. 2. Date Literal Query: Leads Created in Last 30 Days
  3. 3. Retrieve Account Names and Industry
  4. 4. List All Closed Won Opportunities with Amounts
  5. 5. Five Most Recently Created Leads
  6. 6. Average Amount of Closed Won Opportunities
  7. 7. Opportunities Closing in the Next 7 Days
  8. 8. Opportunities with a Close Date in the Current Month
  9. 9. Total Number of Leads in Each Lead Source Category
  10. 10. Accounts with Billing Postal Code Starting with "9"
  11. 11. Opportunities in Negotiation Stage with Amount > $100,000
  12. 12. Opportunities Closing in the Next 14 Days (Sorted by Close Date)
  13. 13. Opportunities Created by a Specific User
  14. 14. SOQL Child-to-Parent: Contact with Account Name
  15. 15. SOQL Child-to-Parent: Opportunity with Account Industry
  16. 16. SOQL Child-to-Parent: Contact with Account Billing Address
  17. 17. SOQL Child-to-Parent: Open Cases with Account Name
  18. 18. SOQL Parent-to-Child: Account with Contacts Subquery
  19. 19. SOQL Parent-to-Child: Account with Open Opportunities
  20. 20. SOQL: Get All Accounts
  21. 21. SOQL: Filter Accounts by Industry
  22. 22. SOQL: Retrieve Top 5 Accounts
  23. 23. SOQL: Sort Accounts by CreatedDate Descending
  24. 24. SOQL: Accounts Whose Name Starts With "A"
  25. 25. SOQL: Contacts That Have an Email Address
  26. 26. SOQL: Opportunities with Amount Greater Than 50,000
  27. 27. SOQL: Retrieve All Closed Won Opportunities
  28. 28. SOQL: Contacts Created Today Using Date Literal
  29. 29. SOQL: Count Total Number of Accounts
  30. 30. SOQL: Parent-to-Child Subquery With LIMIT
  31. 31. SOQL: 10 Most Recently Created Leads
  32. 32. SOQL: Opportunities Closing This Month
  33. 33. SOQL: Filter Accounts Using the IN Operator
  34. 34. SOQL: Find Contacts by Email Domain Using LIKE
  35. 35. SOQL: Accounts of Specific Types Using IN With a Bound List
  36. 36. SOQL: Retrieve Won Opportunities Using the Boolean IsWon Field
  37. 37. SOQL: Leads Not Yet Contacted
  38. 38. Scenario: Retrieve Support Cases Awaiting Customer Reply
Easy SOQLGovernor

1. SOQL Aggregate Rollup

Problem #8 · Salesforce Apex Coding Challenge

Problem Statement

Write a SOQL query using aggregate functions to produce a summary report of Opportunity records grouped by StageName.

For each stage, return the count, total amount, and average amount.

Expected Output Format

Stage         | Count | Total      | Average
Prospecting   |  24   | 1,200,000  | 50,000
Closed Won    |  18   | 4,500,000  | 250,000
Approach
  • 1Use SUM(Amount) totalAmt and AVG(Amount) avgAmt in the SELECT clause.
  • 2Access results with: (Decimal) result.get('totalAmt')
  • 3You can alias each aggregate expression for cleaner access in Apex.
Easy SOQL

2. Date Literal Query: Leads Created in Last 30 Days

Problem #86 · Salesforce Apex Coding Challenge

Problem Statement

Write a method that returns all Lead records created within the last 30 days, ordered newest-first.

Method Signature

public static List<Lead> getRecentLeads()

Key Concept — Date Literals

SOQL date literals let you write time-relative filters without hardcoding dates. They are written without quotes and some accept a numeric suffix (:N):

WHERE CreatedDate >= LAST_N_DAYS:30

Common date literals:

  • TODAY, YESTERDAY, TOMORROW
  • THIS_WEEK, LAST_WEEK, NEXT_WEEK
  • LAST_N_DAYS:n — the past n days (including today)
  • NEXT_N_DAYS:n — the next n days
  • THIS_MONTH, LAST_MONTH, NEXT_MONTH

Constraints

  • Use a date literal — not a hardcoded date string
  • Order by CreatedDate DESC (newest first)
  • Return at least Id, FirstName, LastName, CreatedDate
Approach
  • 1Date literals go directly in WHERE without quotes: WHERE CreatedDate >= LAST_N_DAYS:30
  • 2You can also use = LAST_N_DAYS:30 — it includes all records from the rolling 30-day window.
  • 3ORDER BY CreatedDate DESC puts the most recently created lead first.
Easy SOQL

3. Retrieve Account Names and Industry

Problem #107 · Salesforce Apex Coding Challenge

Problem Statement

Write a SOQL query inside getAccountsWithIndustry() that retrieves all Account Name and Industry fields, ordered alphabetically by Name.

Requirements

  • Return every Account's Name and Industry.
  • Sort the results alphabetically by Account Name.
  • Keep the result set to a reasonable page size (200 records).
Approach
  • 1Your SELECT list needs both Name and Industry from the Account object.
  • 2Consider whether the query should respect field-level security for the running user.
  • 3Sort the list alphabetically by Name.
Easy SOQL

4. List All Closed Won Opportunities with Amounts

Problem #110 · Salesforce Apex Coding Challenge

Problem Statement

List all Closed Won Opportunities with their Name, Amount, and CloseDate, sorted by highest Amount first.

Requirements

  • WHERE StageName = 'Closed Won'
  • SELECT Name, Amount, CloseDate, AccountId
  • ORDER BY Amount DESC
Approach
  • 1StageName = 'Closed Won' — exact stage value, casing matters.
  • 2ORDER BY Amount DESC puts the largest deals first.
  • 3Include CloseDate in SELECT to give callers the win date.
Easy SOQL

5. Five Most Recently Created Leads

Problem #111 · Salesforce Apex Coding Challenge

Problem Statement

Write a SOQL query that retrieves the five most recently created Leads, ordered from newest to oldest.

Requirements

  • Return each Lead's Id, FirstName, LastName, Email, Company, and CreatedDate.
  • Show only the 5 newest Leads, most recent first.
Approach
  • 1CreatedDate is a system field on every Salesforce object.
  • 2ORDER BY CreatedDate DESC puts the newest record first.
  • 3LIMIT 5 caps the result at five records.
Easy SOQLAggregate

6. Average Amount of Closed Won Opportunities

Problem #113 · Salesforce Apex Coding Challenge

Problem Statement

Compute and return the average Amount of all Closed Won Opportunities as a Decimal. Return 0 if no records exist.

Requirements

  • Aggregate the Amount field with an average function, aliasing the aggregate result exactly avgAmt (required for grading)
  • Restrict the aggregate to Opportunities that are Closed Won
  • Access the aggregate value through its avgAmt alias
  • Guard: return 0 if results list is empty
Approach
  • 1Aggregate Amount with an average function over Opportunities filtered to Closed Won, and alias the result avgAmt.
  • 2Access with results[0].get('avgAmt') — the alias must match.
  • 3Guard against empty results before accessing index 0.
Easy SOQLDate Literals

7. Opportunities Closing in the Next 7 Days

Problem #114 · Salesforce Apex Coding Challenge

Problem Statement

Return all Opportunities whose CloseDate falls within the next 7 calendar days, ordered soonest-first.

Key Concept — Date Literals

NEXT_N_DAYS:7 matches any date from tomorrow through 7 days from today (inclusive). No Apex date arithmetic is needed.

Requirements

  • WHERE CloseDate = NEXT_N_DAYS:7
  • ORDER BY CloseDate ASC
Approach
  • 1NEXT_N_DAYS:7 is a SOQL date literal — no Apex Date.today().addDays(7) needed.
  • 2ORDER BY CloseDate ASC shows deals that need attention soonest.
  • 3enforces FLS.
Easy SOQLDate Literals

8. Opportunities with a Close Date in the Current Month

Problem #117 · Salesforce Apex Coding Challenge

Problem Statement

Return all Opportunities whose CloseDate falls within the current calendar month, ordered from earliest to latest close date.

Key Concept

THIS_MONTH covers the entire current month — first day through last day — regardless of today's date.

Requirements

  • Filter to Opportunities whose CloseDate falls in the current calendar month, using a date literal — no date-arithmetic bounds.
  • Sort the result chronologically by CloseDate, earliest first.
Approach
  • 1THIS_MONTH matches any CloseDate in the current calendar month.
  • 2A single date-literal comparison replaces any manual first-day/last-day bounds.
  • 3Sorting ascending by CloseDate gives a chronological view of the month.
Easy SOQLAggregate

9. Total Number of Leads in Each Lead Source Category

Problem #120 · Salesforce Apex Coding Challenge

Problem Statement

Aggregate the Lead object to find the total number of Leads in each Lead Source category, ordered from the most to the least common source.

Requirements

  • SELECT LeadSource, COUNT(Id) total
  • FROM Lead
  • GROUP BY LeadSource
  • ORDER BY COUNT(Id) DESC
Approach
  • 1GROUP BY LeadSource partitions Leads into per-source buckets.
  • 2COUNT(Id) total counts leads per bucket; access with ar.get('total').
  • 3ORDER BY COUNT(Id) DESC puts the most common source first.
Easy SOQL

10. Accounts with Billing Postal Code Starting with "9"

Problem #121 · Salesforce Apex Coding Challenge

Problem Statement

Retrieve all Accounts whose Billing Postal Code starts with the digit "9".

Key Concept — LIKE Operator

LIKE '9%' in SOQL matches any string beginning with "9". The % wildcard matches zero or more characters.

Requirements

  • WHERE BillingPostalCode LIKE '9%'
  • SELECT Id, Name, BillingPostalCode
  • ORDER BY Name ASC
Approach
  • 1LIKE '9%' matches postal codes starting with 9: '9', '90210', '94105', etc.
  • 2The LIKE operator is case-insensitive in SOQL.
  • 3SELECT BillingPostalCode so callers can see what matched.
Easy SOQL

11. Opportunities in Negotiation Stage with Amount > $100,000

Problem #123 · Salesforce Apex Coding Challenge

Problem Statement

Retrieve Opportunities in the "Negotiation" stage that also have an Amount greater than $100,000.

Requirements

  • Filter to Opportunities whose StageName is Negotiation and whose Amount exceeds 100,000
  • Select Id, Name, Amount, StageName, AccountId
  • Sort the results by Amount, highest first
Approach
  • 1Combine both filters: the stage must be Negotiation and the amount must exceed 100000.
  • 2Amount is numeric in SOQL — no $ symbol or commas.
  • 3Sorting by Amount descending surfaces the highest-value negotiations first.
Easy SOQLDate Literals

12. Opportunities Closing in the Next 14 Days (Sorted by Close Date)

Problem #125 · Salesforce Apex Coding Challenge

Problem Statement

List all open Opportunities whose CloseDate is within the next 14 days, sorted soonest-to-close first.

Requirements

  • WHERE CloseDate <= NEXT_N_DAYS:14
  • AND IsClosed = false
  • ORDER BY CloseDate ASC
Approach
  • 1NEXT_N_DAYS:14 is a date literal — CloseDate <= NEXT_N_DAYS:14 covers the next 14 days.
  • 2AND IsClosed = false excludes already-closed deals.
  • 3ORDER BY CloseDate ASC shows deals needing attention soonest.
Easy SOQL

13. Opportunities Created by a Specific User

Problem #132 · Salesforce Apex Coding Challenge

Problem Statement

Return all Opportunities created by a specific user, identified by their Salesforce User Id, ordered most-recent first.

Requirements

  • Filter Opportunities to those whose CreatedById matches the passed-in user Id
  • Method signature: getOpportunitiesCreatedByUser(Id userId)
  • Select Id, Name, Amount, StageName, CreatedDate
  • Sort by CreatedDate, most recent first
Approach
  • 1CreatedById is a standard system field on every Salesforce SObject.
  • 2Bind the method parameter into the filter using a colon prefix, e.g. :userId.
  • 3Sorting by CreatedDate descending shows most recently created opportunities first.
Easy SOQLChild-to-Parent

14. SOQL Child-to-Parent: Contact with Account Name

Problem #184 · Salesforce Apex Coding Challenge

Problem Statement

Write a child-to-parent SOQL query that retrieves a list of Contacts along with the name of each Contact's parent Account.

Requirements

  • Return each Contact's Id, FirstName, LastName, and Email, plus their parent Account's Name.
  • Query the Contact object.
  • Sort alphabetically by LastName, and cap the result at 20 rows.

Key Concept

Use dot notation (Account.Name) to traverse the relationship from child (Contact) to parent (Account).

Approach
  • 1Use dot notation to reach through the parent relationship in the SELECT clause
  • 2Query FROM Contact, not FROM Account
  • 3Sort by LastName, and remember the row cap
Easy SOQLChild-to-Parent

15. SOQL Child-to-Parent: Opportunity with Account Industry

Problem #185 · Salesforce Apex Coding Challenge

Problem Statement

Write a child-to-parent SOQL query that retrieves open Opportunities along with the Industry of their parent Account.

Requirements

  • Return each Opportunity's Id, Name, StageName, CloseDate, and Amount, plus its parent Account's Industry.
  • Only include Opportunities that are still open.
  • Sort by CloseDate, soonest first, and cap the result at 20 rows.
Approach
  • 1Reach the parent Account's Industry field with dot notation in your SELECT clause
  • 2Filter to Opportunities that are not yet closed
  • 3Sort by CloseDate ascending to see soonest closings first
Easy SOQLChild-to-Parent

16. SOQL Child-to-Parent: Contact with Account Billing Address

Problem #186 · Salesforce Apex Coding Challenge

Problem Statement

Retrieve Contacts along with their parent Account's billing address fields (City, State, Country) using child-to-parent SOQL.

Requirements

  • Return each Contact's Id, FirstName, LastName, and Email, plus their parent Account's City, State, and Country billing fields.
  • Only include Contacts whose Account has a billing city on file.
  • Sort by the parent Account's billing country, and cap the result at 20 rows.
Approach
  • 1You can filter on a related object's field the same way you'd filter on the base object's
  • 2You'll need three separate parent-field references in the SELECT clause for the billing address
  • 3You can sort by a parent field just like a regular one
Easy SOQLChild-to-Parent

17. SOQL Child-to-Parent: Open Cases with Account Name

Problem #187 · Salesforce Apex Coding Challenge

Problem Statement

Write a child-to-parent SOQL query that retrieves open Cases with their parent Account name.

Requirements

  • Return each Case's Id, CaseNumber, Subject, Status, and Priority, plus its parent Account's Name.
  • Only include Cases that are not yet closed.
  • Sort by Priority, and cap the result at 20 rows.
Approach
  • 1Reach the parent account's name with dot notation in the SELECT clause
  • 2Filter out Cases whose Status is 'Closed'
  • 3Sort ascending by Priority
Easy SOQLParent-to-Child

18. SOQL Parent-to-Child: Account with Contacts Subquery

Problem #194 · Salesforce Apex Coding Challenge

Problem Statement

Write a parent-to-child SOQL query that retrieves Accounts together with a list of their related Contacts using a subquery.

Requirements

  • Return each Account's Id, Name, Phone, and Website, along with a nested list of its related contacts' Id, FirstName, LastName, and Email.
  • Query the Account object.
  • Sort alphabetically by Name and cap the results at 10 rows.

Key Concept

Parent-to-child uses a subquery in parentheses to pull related child records inline. Note the plural relationship name for Contacts, not the singular object name.

Approach
  • 1Parent-to-child uses a subquery in parentheses to embed related child records in the result.
  • 2The relationship name used in a child subquery is the plural version of the child object's name, not the singular object name.
  • 3The subquery goes inside the outer SELECT's field list, not in a WHERE clause.
Easy SOQLParent-to-Child

19. SOQL Parent-to-Child: Account with Open Opportunities

Problem #195 · Salesforce Apex Coding Challenge

Problem Statement

Retrieve Accounts with a subquery for their open Opportunities. The subquery should filter and order the child records.

Requirements

  • For each Account, return its Id, Name, Industry, and AnnualRevenue, plus a nested list of its still-open opportunities' Id, Name, StageName, Amount, and CloseDate.
  • Sort the nested opportunities by their close date, soonest first.
  • Sort the outer Account results alphabetically by Name and cap them at 10 rows.
Approach
  • 1A child subquery's relationship name is the plural form of the child object.
  • 2A subquery can have its own filter condition to restrict which child records come back, independent of the outer query's filters.
  • 3Sorting inside a subquery orders only the nested child records, separately from any outer ORDER BY.

Halfway there — solve them live

Every problem above runs in a real in-browser Apex editor with instant pass/fail feedback and best-practice linting. No Salesforce org needed.

Create Free Account →
Easy SOQL

20. SOQL: Get All Accounts

Problem #250 · Salesforce Apex Coding Challenge

Problem Statement

Inside SOQLPracticeService, implement getAllAccounts() that returns every Account with its Id, Name, and Industry fields.

Requirements

  • Return each Account's Id, Name, and Industry.
  • Query the Account object with no filtering — every Account should come back.
  • Return type: List<Account>
Approach
  • 1The simplest SOQL query has no WHERE clause — it returns all rows.
  • 2Always include Id so callers can reference each record.
  • 3Return the query result directly: return [SELECT … FROM Account];
Easy SOQL

21. SOQL: Filter Accounts by Industry

Problem #251 · Salesforce Apex Coding Challenge

Problem Statement

Implement getAccountsByIndustry(String industryName) that returns all Accounts whose Industry matches the given parameter.

Requirements

  • Return each matching Account's Id, Name, and Industry.
  • Query the Account object.
  • Filter to Accounts whose Industry equals the value passed into the method, using a bind variable rather than string concatenation.
Approach
  • 1Use a colon (:) to bind an Apex variable directly into a SOQL filter condition, e.g. WHERE SomeField = :someVariable.
  • 2Bind variables prevent SOQL injection — never concatenate strings into a query.
  • 3The parameter name in the bind must match exactly the Apex variable name.
Easy SOQL

22. SOQL: Retrieve Top 5 Accounts

Problem #252 · Salesforce Apex Coding Challenge

Problem Statement

Implement getTopAccounts() that returns only the first 5 Account records with Id and Name.

Requirements

  • Return each Account's Id and Name.
  • Query the Account object.
  • Cap the number of records returned at 5.
Approach
  • 1A LIMIT clause caps the result set at a fixed number of records.
  • 2Without ORDER BY the order is undefined; add ORDER BY Name if you need determinism.
  • 3LIMIT must be the last clause in the query (after ORDER BY).
Easy SOQL

23. SOQL: Sort Accounts by CreatedDate Descending

Problem #253 · Salesforce Apex Coding Challenge

Problem Statement

Implement getAccountsSorted() that returns all Accounts sorted from newest to oldest by CreatedDate.

Requirements

  • Return the Id, Name, and CreatedDate of every Account
  • Query the Account object
  • Sort the results so the most recently created Account comes first
Approach
  • 1ORDER BY field DESC returns largest/newest values first.
  • 2CreatedDate is a system field automatically set on every record.
  • 3You can chain multiple sort fields: ORDER BY CreatedDate DESC, Name ASC.
Easy SOQL

24. SOQL: Accounts Whose Name Starts With "A"

Problem #254 · Salesforce Apex Coding Challenge

Problem Statement

Implement getAccountsStartsWithA() that returns all Accounts whose Name begins with the letter "A".

Requirements

  • SELECT Id, Name
  • WHERE Name LIKE 'A%'
  • The % wildcard matches any suffix
Approach
  • 1LIKE 'A%' matches any string starting with A followed by any characters.
  • 2% is the multi-character wildcard in SOQL LIKE (same as SQL).
  • 3LIKE is case-insensitive in SOQL, so 'A%' also matches 'apex', 'ACME', etc.
Easy SOQL

25. SOQL: Contacts That Have an Email Address

Problem #255 · Salesforce Apex Coding Challenge

Problem Statement

Implement getContactsWithEmail() that returns all Contacts where the Email field is populated (not null).

Requirements

  • Return the Id, FirstName, LastName, and Email of matching Contacts
  • Query the Contact object
  • Exclude any Contact whose Email field is blank
Approach
  • 1Use WHERE Email != null to exclude contacts with no email.
  • 2In SOQL, != null and <> null are both valid null-check operators.
  • 3Always SELECT the fields you intend to display or process.
Easy SOQL

26. SOQL: Opportunities with Amount Greater Than 50,000

Problem #256 · Salesforce Apex Coding Challenge

Problem Statement

Implement getHighValueOpportunities() that returns all Opportunities with Amount greater than 50,000.

Requirements

  • Return the Id, Name, and Amount of matching Opportunities
  • Query the Opportunity object
  • Only include records whose Amount is strictly greater than 50,000
Approach
  • 1Use the > operator for numeric comparisons in SOQL.
  • 2Amount is a Currency field — no quotes needed around the numeric value.
  • 3Records where Amount is null will not satisfy Amount > 50000.
Easy SOQL

27. SOQL: Retrieve All Closed Won Opportunities

Problem #257 · Salesforce Apex Coding Challenge

Problem Statement

Implement getClosedWonOpps() that returns all Opportunities in the "Closed Won" stage.

Requirements

  • Return the Id, Name, and StageName of matching Opportunities
  • Query the Opportunity object
  • Only include records whose stage is exactly "Closed Won"
Approach
  • 1The stage value is 'Closed Won' — exact casing matters in SOQL string comparisons.
  • 2StageName is a picklist field; its API value must match exactly.
  • 3String literals in SOQL use single quotes, not double quotes.
Easy SOQL

28. SOQL: Contacts Created Today Using Date Literal

Problem #258 · Salesforce Apex Coding Challenge

Problem Statement

Implement getTodayContacts() that returns all Contacts created today using a SOQL date literal.

Requirements

  • Return the Id and Name of matching Contacts
  • Query the Contact object
  • Only include records whose CreatedDate falls within the current day, expressed using a SOQL date literal rather than a hardcoded date

SOQL Date Literals

Date literals like TODAY, YESTERDAY, THIS_WEEK, LAST_N_DAYS:n are evaluated at query time in the user's timezone.

Approach
  • 1TODAY is a SOQL date literal — no quotes, no bind variable needed.
  • 2CreatedDate is a DateTime field; using = TODAY matches the entire current day.
  • 3Other useful literals: YESTERDAY, THIS_WEEK, THIS_MONTH, LAST_N_DAYS:7.
Easy SOQLAggregate

29. SOQL: Count Total Number of Accounts

Problem #259 · Salesforce Apex Coding Challenge

Problem Statement

Implement getAccountCount() that returns the total number of Account records as an Integer.

Requirements

  • Use SELECT COUNT() — no field name inside COUNT()
  • FROM Account
  • Return type: Integer
  • A COUNT() query returns an Integer directly, not a list
Approach
  • 1SELECT COUNT() (no field name) returns an Integer directly — no AggregateResult needed.
  • 2This is the only SOQL query form that returns a scalar Integer, not a List.
  • 3Do not confuse with COUNT(Id), which requires AggregateResult[] and GROUP BY.
Easy SOQLSubquery

30. SOQL: Parent-to-Child Subquery With LIMIT

Problem #272 · Salesforce Apex Coding Challenge

Problem Statement

Implement getAccountsWithLimitedContacts() that fetches each Account with at most 3 of its Contacts.

Requirements

  • Return every Account's Id and Name
  • For each Account, include a nested list of its Contacts (Id and LastName), capped at 3 per Account
Approach
  • 1LIMIT inside a subquery caps child records per parent, not total.
  • 2Combine with ORDER BY inside the subquery to get the "first 3" by a meaningful field.
  • 3LIMIT 3 keeps the result set small and avoids heap-size issues.
Easy SOQL

31. SOQL: 10 Most Recently Created Leads

Problem #275 · Salesforce Apex Coding Challenge

Problem Statement

Implement getRecentLeads() that returns the 10 most recently created Leads with their Name and Company.

Requirements

  • Return the Id, Name, and Company of matching Leads
  • Query the Lead object
  • Sort so the most recently created Lead comes first, and cap the results at 10 records
Approach
  • 1Sort by CreatedDate descending so the newest records come first, then cap the result at the required count.
  • 2Always put LIMIT after ORDER BY (it is the last clause).
  • 3Company is a required field on Lead in standard Salesforce orgs.
Easy SOQL

32. SOQL: Opportunities Closing This Month

Problem #277 · Salesforce Apex Coding Challenge

Problem Statement

Implement getThisMonthOpportunities() that returns all Opportunities whose CloseDate falls within the current calendar month.

Requirements

  • Return the Id, Name, and CloseDate of matching Opportunities
  • Query the Opportunity object
  • Only include records whose CloseDate falls in the current calendar month, expressed using a SOQL date literal rather than a hardcoded date range

Common Date Literals

  • TODAY, YESTERDAY
  • THIS_WEEK, LAST_WEEK, NEXT_WEEK
  • THIS_MONTH, LAST_MONTH, NEXT_MONTH
  • LAST_N_DAYS:n, NEXT_N_DAYS:n
Approach
  • 1THIS_MONTH covers from the 1st to the last day of the current month.
  • 2CloseDate is a Date field on Opportunity (not DateTime), so THIS_MONTH works directly.
  • 3Date literals are evaluated relative to the running user's timezone.
Easy SOQL

33. SOQL: Filter Accounts Using the IN Operator

Problem #278 · Salesforce Apex Coding Challenge

Problem Statement

Implement getAccountsByIndustries() that returns Accounts in the Banking, IT, or Healthcare industries using the IN operator.

Requirements

  • Return the Id, Name, and Industry of matching Accounts
  • Query the Account object
  • Only include records whose Industry is one of Banking, IT, or Healthcare, using the IN operator against that set of values

IN Operator

IN is equivalent to multiple OR conditions. It accepts a comma-separated list of values enclosed in parentheses.

Approach
  • 1IN ('v1','v2','v3') is a concise alternative to three OR conditions.
  • 2You can also bind an Apex Set or List: WHERE Industry IN :mySet.
  • 3IN is case-sensitive for string picklist values — match the API label exactly.
Easy SOQL

34. SOQL: Find Contacts by Email Domain Using LIKE

Problem #395 · Salesforce Apex Coding Challenge

Problem Statement

Write an Apex class ContactDomainQuery with a method getContactsByDomain(String domain) that returns every Contact whose Email ends with @<domain> (e.g. passing "acme.com" should match jane@acme.com).

Requirements

  • Build the wildcard pattern into a local String variable first, then bind that variable into the query's LIKE comparison — never concatenate domain directly into the SOQL string.
  • Include WITH SECURITY_ENFORCED and an ORDER BY / LIMIT.

Best Practices

  • Binding a pre-built String variable (:pattern) instead of splicing user input into the query text is what keeps this SOQL-injection-safe — Apex only allows binding a simple variable reference, not an inline expression, inside LIKE :('%@' + domain).
  • WITH SECURITY_ENFORCED enforces field- and object-level security for the running user.
  • Always pair an unbounded WHERE clause with a sane LIMIT.
Approach
  • 1String pattern = '%@' + domain; builds the wildcard once, before the query.
  • 2Apex only allows a plain bind variable after LIKE — an inline expression like LIKE :('%@' + domain) does not compile.
  • 3WITH SECURITY_ENFORCED goes right after the WHERE clause (or FROM if there is no WHERE).
Easy SOQL

35. SOQL: Accounts of Specific Types Using IN With a Bound List

Problem #405 · Salesforce Apex Coding Challenge

Problem Statement

Write an Apex class AccountsByTypeQuery with a method getAccountsByTypes(List<String> types) that returns every Account whose Type is one of the values in the given list.

Requirements

  • Filter to Accounts whose Type matches any value in the bound list parameter.
  • Order results by Name ascending.

Best Practices

  • Binding a List<String> parameter directly into an IN clause is the standard, injection-safe way to filter against a caller-supplied set of values.
  • Always pair with LIMIT even when the input list is short.
Approach
  • 1A List parameter can be bound directly into an IN filter — no need to build a Set first.
  • 2Filtering with IN against the bound list matches any Account whose Type appears in it.
  • 3Ordering by Name ascending keeps results deterministic for testing and display.
Easy SOQL

36. SOQL: Retrieve Won Opportunities Using the Boolean IsWon Field

Problem #406 · Salesforce Apex Coding Challenge

Problem Statement

Write an Apex class WonOpportunitiesQuery with a method getWonOpportunities() that returns every won Opportunity, ordered from highest to lowest Amount.

Requirements

  • Filter using the standard boolean field IsWon = true — not a picklist comparison against StageName.
  • Order by Amount DESC.

Best Practices

  • IsWon is a formula-backed boolean that's true for exactly the stage(s) flagged as "won" in Stage Settings — filtering on it is more robust than hardcoding a Stage name like 'Closed Won', since org-specific stage names can vary.
Approach
  • 1IsWon is a Boolean field — compare it with = true, no quotes.
  • 2Filtering on IsWon is more robust than hardcoding a StageName string, since stage names can be customized per org.
  • 3ORDER BY Amount DESC puts the largest deals first.
Easy SOQL

37. SOQL: Leads Not Yet Contacted

Problem #413 · Salesforce Apex Coding Challenge

Problem Statement

Write an Apex class UncontactedLeadsQuery with a method getUncontactedLeads() that returns every Lead still at the default "Open - Not Contacted" status, oldest first.

Requirements

  • Filter Leads down to exactly that Status value.
  • Sort so the oldest, longest-waiting Leads surface first.

Best Practices

  • Ordering oldest-first on a queue-style report (like uncontacted Leads) surfaces the records most at risk of going stale, which is usually the actionable priority.
Approach
  • 1Status is a picklist on Lead, compared here as a plain string literal.
  • 2Sorting by creation date ascending puts the oldest, longest-waiting Leads first.
  • 3A LIMIT clause keeps the query safe even if this list grows large.
Easy SOQL

38. Scenario: Retrieve Support Cases Awaiting Customer Reply

Problem #438 · Salesforce Apex Coding Challenge

Business Scenario

The support team wants a queue of Cases currently waiting on the customer to respond, oldest first, so nothing silently ages out.

Requirements

  • Write an Apex class AwaitingReplyCasesQuery with a method getCasesAwaitingCustomerReply().
  • Only include Cases whose status is Awaiting Customer Response.
  • Sort the results so the longest-waiting Cases surface first (oldest last-modified first).
Approach
  • 1Status is a plain string comparison against the 'Awaiting Customer Response' value.
  • 2Sort so the oldest waiting Cases come first — the ones most at risk of being forgotten.
  • 3Always pair an unbounded filter with a LIMIT.

Practice All 38 Problems Free

Write and run real Apex code right in your browser — instant pass/fail feedback, best-practice linting, and governor limit monitoring. No Salesforce org needed.

Create Free Account → Explore All Problems
More Practice Topics
About ApexArena

ApexArena is a free, browser-based Salesforce Apex coding practice platform covering every major topic tested on the Salesforce Platform Developer I (PD1) and Platform Developer II (PD2) certification exams. All problems run directly in your browser with instant pass/fail feedback, best-practice linting (SOQL in loops, DML in loops, empty catch blocks), and governor limit monitoring — no Salesforce Developer Edition org required.

Related tutorials: Apex Triggers · SOQL · Batch Apex · Interview Q&A · Governor Limits