SOQL Practice Problem
- Find the total number of Opportunities for each Account.
SELECT Account.Name, count(Id) FROM Opportunity GROUP BY Account.Name
- List all closed Won Opportunities along with their amounts.
SELECT Name, Amount FROM Opportunity WHERE StageName = 'Closed Won'
- Identify the five most recently created Leads.
SELECT Id FROM Lead ORDER BY CreatedDate DESC LIMIT 5
- Retrieve Account names and their associated Opportunities where the Opportunity Amount is greater than $10,000
SELECT Account.Name, Amount FROM Opportunity WHERE Amount > 10000
- Find the average amount of all closed Won Opportunities.
SELECT avg(Amount) FROM Opportunity WHERE StageName = 'Closed Won'
- Find the Account with the maximum number of Opportunities.
SELECT Account.Name, count(Id) FROM Opportunity Group by Account.Name order by count(Id) DESC LIMIT 1
- List the Opportunities that are due to close in the next 7 days.
SELECT Id, Name, CloseDate FROM Opportunity WHERE CloseDate = NEXT_N_DAYS:7
TODAY
: Refers to the current date.YESTERDAY
: Refers to the previous day.LAST_N_DAYS:n
: Filters records for the pastn
days.THIS_WEEK
,THIS_MONTH
, etc.: Filters records for the current week, month, etc
- List the Opportunities that have a Close Date in the current month.
SELECT Id, Name FROM Opportunity WHERE CloseDate = THIS_MONTH
- Retrieve the names of all Accounts that have both Opportunities and Cases associated with them.
SELECT Name FROM Account WHERE Id IN (SELECT AccountId FROM Case) AND ID IN (SELECT AccountId FROM Opportunity)
- Identify the Opportunities that have not been updated in the last 3 days.
SELECT Name FROM Opportunity WHERE LastModifiedDate >= LAST_N_DAYS
The
LAST_N_DAYS
literal includes today as part of the "last N days."It can be used with any date or datetime field like
CreatedDate
,LastModifiedDate
, or any custom date fields.
- Find the total number of Leads in each Lead Source category.
SELECT LeadSource, count(Id) FROM Lead GROUP BY LeadSource
- Find the Opportunities with a Stage of “Closed Won” and an Amount greater than $1000.
SELECT Name, Amount FROM Opportunity WHERE StageName = 'Closed Won' AND Amount > 100
- Retrieve the names of Accounts along with the total amount of all their associated Opportunities.
SELECT Account.Name, SUM(Amount) FROM Opportunity GROUP BY Account.Name
- Find the Opportunities with a Close Date in the next 14 days and sort them by Close Date in ascending order.
SELECT Name, CloseDate FROM Opportunity WHERE CloseDate <= NEXT_N_DAYS:14 ORDER BY CloseDate
- Retrieve the top 3 Opportunities with the highest Amount for each Account.
SELECT Id, Name, (SELECT Name, Amount FROM Opportunities ORDER BY Amount DESC LIMIT 3) FROM Account
- Find the Accounts that have not been modified in the last 60 days.
SELECT Id, Name FROM Account WHERE LastModifiedDate >= LAST_N_DAYS:60