Can we make a check on WHERE clause of a SOQL query for comparing 2 date fields availability? My requirement is, I want to get the response from query based on data availability on two different fields. I have 2 date fields (Date_A__c and Date_B__c). My requirement is to make a check on a single query that if data is present in Date_A__c, the query should return with its data, but if data is unavailable in Date_A__c, the query should return with Date_B__c data. Is this condition possible to write in WHERE clause.

  • 1
    You can not do this in a query using just those two field. You can create a formula field that evaluates to the correct value and use that in your query. – rael_kid Jul 20 '18 at 7:28
  • @KhushbooDua why you can not use a formula field in a where condition!? – Sergej Utko Jul 20 '18 at 7:30

You can not do it with SOQL. But you can do it for sure with APEX method use a SOQL query. A SOQL query reads data from a data store based on conditions you enter. The APEX method returns the data:

public Date myMethod()
    MyObject__c m = [Select Date_A__c, Date_B__c
                     From MyObject__c
                     Where CreatedDate = LAST_WEEK];
    if(m.Date_A__c != null)
        return m.Date_A__c;

    return m.Date_B__c;

Yes this is possible using single query.

Make your query

WHERE Date_A__c != null OR Date_B__c != null

and when you iterate over it then simply put an if condition

if(Object.Date_A__c != null) {
    //run code here
else {
    //run code here

If you are looking for a purely SOQL query then I think you can create a custom formula field (checkbox) can use that in the query.

Otherwise, you will have to use apex to filter the data which some folks have already mentioned in other comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.