This guide walks through 33 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.
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.
Stage | Count | Total | Average Prospecting | 24 | 1,200,000 | 50,000 Closed Won | 18 | 4,500,000 | 250,000
Write a method that returns all Lead records
created within the last 30 days, ordered newest-first.
public static List<Lead> getRecentLeads()
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, TOMORROWTHIS_WEEK, LAST_WEEK, NEXT_WEEKLAST_N_DAYS:n — the past n days (including today)NEXT_N_DAYS:n — the next n daysTHIS_MONTH, LAST_MONTH, NEXT_MONTHCreatedDate DESC (newest first)Id, FirstName, LastName, CreatedDateWrite a SOQL query inside getAccountsWithIndustry() that retrieves
all Account Name and Industry fields,
ordered alphabetically by Name.
Name and IndustryAccountName ASCList all Closed Won Opportunities with their Name, Amount, and CloseDate, sorted by highest Amount first.
StageName = 'Closed Won'Name, Amount, CloseDate, AccountIdAmount DESCWrite a SOQL query that retrieves the five most recently created Leads, ordered from newest to oldest.
Id, FirstName, LastName, Email, Company, CreatedDateLeadCreatedDate DESC5Compute and return the average Amount of all Closed Won
Opportunities as a Decimal. Return 0 if no records exist.
AVG(Amount) avgAmtStageName = 'Closed Won'(Decimal) results[0].get('avgAmt')Return all Opportunities whose CloseDate falls within the next 7 calendar days, ordered soonest-first.
NEXT_N_DAYS:7 matches any date from tomorrow through 7 days
from today (inclusive). No Apex date arithmetic is needed.
CloseDate = NEXT_N_DAYS:7CloseDate ASCReturn all Opportunities whose CloseDate falls within the current calendar month, ordered from earliest to latest close date.
THIS_MONTH covers the entire current month — first day through
last day — regardless of today's date.
CloseDate = THIS_MONTHCloseDate ASCAggregate the Lead object to find the total number of Leads in each Lead Source category, ordered from the most to the least common source.
LeadSource, COUNT(Id) totalLeadLeadSourceCOUNT(Id) DESCRetrieve all Accounts whose Billing Postal Code starts with the digit "9".
LIKE '9%' in SOQL matches any string beginning with "9".
The % wildcard matches zero or more characters.
BillingPostalCode LIKE '9%'Id, Name, BillingPostalCodeName ASCRetrieve Opportunities in the "Negotiation" stage that also have an Amount greater than $100,000.
StageName = 'Negotiation' AND Amount > 100000Id, Name, Amount, StageName, AccountIdAmount DESCList all open Opportunities whose CloseDate is within the next 14 days, sorted soonest-to-close first.
CloseDate <= NEXT_N_DAYS:14IsClosed = falseCloseDate ASCReturn all Opportunities created by a specific user, identified by their Salesforce User Id, ordered most-recent first.
CreatedById = :userIdgetOpportunitiesCreatedByUser(Id userId)Id, Name, Amount, StageName, CreatedDateCreatedDate DESCWrite a child-to-parent SOQL query that retrieves a list of Contacts along with the name of each Contact's parent Account.
Id, FirstName, LastName, Email, Account.NameContactLastName ASC, LIMIT 20Use dot notation (Account.Name) to traverse the relationship from child (Contact) to parent (Account).
Write a child-to-parent SOQL query that retrieves open Opportunities along with the Industry of their parent Account.
Id, Name, StageName, CloseDate, Amount, Account.IndustryOpportunity WHERE IsClosed = falseCloseDate ASC, LIMIT 20Retrieve Contacts along with their parent Account's billing address fields (City, State, Country) using child-to-parent SOQL.
Id, FirstName, LastName, Email, Account.BillingCity, Account.BillingState, Account.BillingCountryContact WHERE Account.BillingCity != nullAccount.BillingCountry ASC, LIMIT 20Write a child-to-parent SOQL query that retrieves open Cases with their parent Account name.
Id, CaseNumber, Subject, Status, Priority, Account.NameCase WHERE Status != 'Closed'Priority ASC, LIMIT 20Every 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 →Write a parent-to-child SOQL query that retrieves Accounts together with a list of their related Contacts using a subquery.
Id, Name, Phone, Website, plus a subquery: (SELECT Id, FirstName, LastName, Email FROM Contacts)AccountName ASC, LIMIT 10Parent-to-child uses a subquery in parentheses: (SELECT ... FROM Contacts). Note the plural relationship name Contacts, not Contact.
Retrieve Accounts with a subquery for their open Opportunities. The subquery should filter and order the child records.
(SELECT Id, Name, StageName, Amount, CloseDate FROM Opportunities WHERE IsClosed = false ORDER BY CloseDate ASC)Account, ORDER BY Name ASC, LIMIT 10Inside SOQLPracticeService, implement getAllAccounts()
that returns every Account with its Id,
Name, and Industry fields.
Id, Name, IndustryAccountList<Account>Implement getAccountsByIndustry(String industryName) that returns
all Accounts whose Industry matches the given parameter.
Id, Name, IndustryAccountIndustry = :industryName (bind variable)Implement getTopAccounts() that returns only the first
5 Account records with Id and Name.
Id, NameAccount5Implement getAccountsSorted() that returns all Accounts
sorted from newest to oldest by CreatedDate.
Id, Name, CreatedDateAccountCreatedDate DESCImplement getAccountsStartsWithA() that returns all Accounts
whose Name begins with the letter "A".
Id, NameName LIKE 'A%'% wildcard matches any suffixImplement getContactsWithEmail() that returns all Contacts
where the Email field is populated (not null).
Id, FirstName, LastName, EmailContactEmail != nullImplement getHighValueOpportunities() that returns all
Opportunities with Amount greater than 50,000.
Id, Name, AmountOpportunityAmount > 50000Implement getClosedWonOpps() that returns all Opportunities
in the "Closed Won" stage.
Id, Name, StageNameOpportunityStageName = 'Closed Won'Implement getTodayContacts() that returns all Contacts
created today using a SOQL date literal.
Id, NameContactCreatedDate = TODAYDate literals like TODAY, YESTERDAY,
THIS_WEEK, LAST_N_DAYS:n are evaluated at query
time in the user's timezone.
Implement getAccountCount() that returns the
total number of Account records as an Integer.
SELECT COUNT() — no field name inside COUNT()AccountIntegerImplement getAccountsWithLimitedContacts() that fetches each
Account with at most 3 of its Contacts.
Id, Name FROM Account(SELECT Id, LastName FROM Contacts LIMIT 3)Implement getRecentLeads() that returns the
10 most recently created Leads with their Name
and Company.
Id, Name, CompanyLeadCreatedDate DESC10Implement getThisMonthOpportunities() that returns all
Opportunities whose CloseDate falls within the
current calendar month.
Id, Name, CloseDateOpportunityCloseDate = THIS_MONTHTODAY, YESTERDAYTHIS_WEEK, LAST_WEEK, NEXT_WEEKTHIS_MONTH, LAST_MONTH, NEXT_MONTHLAST_N_DAYS:n, NEXT_N_DAYS:nImplement getAccountsByIndustries() that returns Accounts
in the Banking, IT, or Healthcare industries using the
IN operator.
Id, Name, IndustryAccountIndustry IN ('Banking', 'IT', 'Healthcare')IN is equivalent to multiple OR conditions.
It accepts a comma-separated list of values enclosed in parentheses.
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 ProblemsApexArena 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