SOQL Practice Problem

·

3 min read

  1. Find the total number of Opportunities for each Account.
SELECT Account.Name, count(Id) FROM Opportunity GROUP BY Account.Name
  1. List all closed Won Opportunities along with their amounts.
SELECT Name, Amount FROM Opportunity WHERE StageName = 'Closed Won'
  1. Identify the five most recently created Leads.
SELECT Id FROM Lead ORDER BY CreatedDate DESC LIMIT 5
  1. 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
  1. Find the average amount of all closed Won Opportunities.
SELECT avg(Amount) FROM Opportunity WHERE StageName = 'Closed Won'
  1. 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
  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 past n days.

  • THIS_WEEK, THIS_MONTH, etc.: Filters records for the current week, month, etc

  1. List the Opportunities that have a Close Date in the current month.
SELECT Id, Name FROM Opportunity WHERE CloseDate = THIS_MONTH
  1. 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)
  1. 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.

  1. Find the total number of Leads in each Lead Source category.
SELECT LeadSource, count(Id) FROM Lead GROUP BY LeadSource
  1. 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
  1. 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
  1. 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
  1. 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
  1. Find the Accounts that have not been modified in the last 60 days.
SELECT Id, Name FROM Account WHERE LastModifiedDate >= LAST_N_DAYS:60