+ Start a Discussion
Vinay Temburnikar 7Vinay Temburnikar 7 

What is the correct syntax to combine OR and AND in soql query?

Need a query that basically says

(ExposeCase = true OR CreatedByID = UserInfo.getUserId()) AND isClosed = false

which would be in the following syntax and sort of a combination of these:

soql += ' Where CreatedById = \'' + UserInfo.getUserId() + '\' OR Expose_Case__c = true';

soql += ' Where Expose_Case__c = true AND isClosed = false';

I am unable to figure out the syntax. I've tried the following 

soql += ' Where CreatedById = \'' + UserInfo.getUserId() + '\' OR Expose_Case__c = true' + 'AND isClosed = false';

Best Answer chosen by Vinay Temburnikar 7
Abdul KhatriAbdul Khatri
Hi Vinay,

Using Dynamic SOQL
soql = 'SELECT Id FROM .... '; 
soql += ' WHERE (CreatedById = \'' + UserInfo.getUserId() + '\'' OR Expose_Case__c = true)'; 
soql += ' AND isClosed = false';

Using Static SOQL
[SELECT Id FROM .... WHERE (CreatedById = :UserInfo.getUserId() OR Expose_Case__c = true) AND isClosed = false];

I hope this helps.
 

All Answers

Abdul KhatriAbdul Khatri
Hi Vinay,

Using Dynamic SOQL
soql = 'SELECT Id FROM .... '; 
soql += ' WHERE (CreatedById = \'' + UserInfo.getUserId() + '\'' OR Expose_Case__c = true)'; 
soql += ' AND isClosed = false';

Using Static SOQL
[SELECT Id FROM .... WHERE (CreatedById = :UserInfo.getUserId() OR Expose_Case__c = true) AND isClosed = false];

I hope this helps.
 
This was selected as the best answer
RituSharmaRituSharma
Use brackets i.e. ( and ) as per your requirement. Something like (1 and 2) or (3 and 4).