Now that we have the tools in our tool belt, let's learn to use them together. Just like in Apex, we use parentheses to separate related conditions.
Back to our 💲big money Opportunities, to get those that have an Amount more than $100,000 AND
those that are in either Negotiation OR
Proposal, OR
Perception Analysis.
SELECT Name, Amount, StageName FROM Opportunity WHERE Amount > 100000 AND (StageName ='Negotiation/Review' OR StageName ='Proposal/Price Quote' OR StageName ='Perception Analysis')
Name | Amount | StageName |
---|---|---|
United Oil Office Portable Generators | 125000 | Negotiation/Review |
United Oil Refinery Generators | 270000 | Proposal/Price Quote |
United Oil Installations | 270000 | Negotiation/Review |
Express Logistics SLA | 120000 | Perception Analysis |
Notably, whenever we start mixing OR
and AND
together, we must employ parentheses to isolate the OR
conditions. To show that, take the following SOQL statement:
SELECT Name, StageName, Type, IsClosed FROM Opportunity WHERE StageName ='Negotiation/Review' AND Type = 'New Customer' OR IsClosed =true
This could be interpreted as either of the following scenarios, which would provide different results and thus SOQL simply returns an error. unexpected token: OR
:
(StageName ='Negotiation/Review' AND Type = 'New Customer') OR IsClosed =true
StageName ='Negotiation/Review' AND (Type = 'New Customer' OR IsClosed =true)
With these parentheses and knowhow of the AND
and OR
operators, we can pile on the conditions.
Consider the following SOQL query to find all Accounts with specific criteria: The Type should neither be 'Prospect' nor blank; the Annual Revenue must exceed $10,000,000; and the Industry should be either 'Energy' or 'Consulting'. We use the AND logical operator to combine these conditions, ensuring each must be true, while the OR operator is used to allow for either of the two industries.
SELECT Name, Type, Industry, AnnualRevenue FROM Account WHERE Type != 'Prospect' AND Type != null AND AnnualRevenue > 10000000 AND (Industry = 'Energy' OR Industry ='Consulting')
Name | Type | Industry | AnnualRevenue |
---|---|---|---|
Dickenson plc | Customer - Channel | Consulting | 50000000 |
United Oil & Gas Corp. | Customer - Direct | Energy | 5600000000 |
While not pretty, it gets the job done. In a later course, you'll learn some alternative ways to write this query.