function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Michael CerulloMichael Cerullo 

Checking that a SOQL is not empty before working with it

I want to make sure a SOQL is not empty before I start working with it.  Is there a way to perform the below code without using 2 SOQL statements?  Thanks in advance for your help!

Account[] alist = new Account[]{};

if(![SELECT Id FROM Account WHERE LastModifiedDate = TODAY].isEmpty()){
     alist = [SELECT Id FROM Account WHERE LastModifiedDate = TODAY];
     for(Account a : alist){
          //do some code...
     }
}
 
Best Answer chosen by Michael Cerullo
Vishal_GuptaVishal_Gupta
Hi Michael,

Please use the below code :

for(Account acc : [SELECT Id FROM Account WHERE LastModifiedDate = TODAY])
{
    //Implement your logic here
}

In above code, for loop execute only if list return the records.

Thanks,
Vishal 

All Answers

William TranWilliam Tran
try this (I have not tested it, but conceptually, it should work):

Account[] alist = new Account[]{};

if([SELECT count() FROM Account WHERE LastModifiedDate = TODAY]>0){
     alist = [SELECT Id FROM Account WHERE LastModifiedDate = TODAY];
     for(Account a : alist){
          //do some code...
     }
}

Thx
Michael CerulloMichael Cerullo
The problem is if that SOQL returns 0 results, it will throw a null pointer exception.
Amit Chaudhary 8Amit Chaudhary 8
Please try below code. This will not give u error
List<Account> alist = [SELECT Id FROM Account WHERE LastModifiedDate = TODAY];
	
	if( alist != null && alist.size() > 0 )
	{
		for(Account a : alist)
		{
		  //do some code...
		}
	}
If still above will give error then please share your full code
 
Vishal_GuptaVishal_Gupta
Hi Michael,

Please use the below code :

for(Account acc : [SELECT Id FROM Account WHERE LastModifiedDate = TODAY])
{
    //Implement your logic here
}

In above code, for loop execute only if list return the records.

Thanks,
Vishal 
This was selected as the best answer