Any reason to skip DML on empty lists?

In parts of my code I have DML statements with an if around to only do the DML if the list is not empty:

if( !recordsToUpdate.isEmpty() ) {
   update recordsToUpdate;
}

Couldn’t I just write?

update recordsToUpdate;

Or would I provoke errors or needlessly consumed limits by doing that?

Answer

Good question, I’ve never considered it before…

i’ve just assumed the platform will play fair and I’m pleased to find it does!

System.debug('Before DmlStatements : ' + Limits.getLimitDmlStatements());
System.debug('Before DmlRows : ' + Limits.getDmlRows());
insert new List<Account>();
System.debug('After DmlStatements : ' + Limits.getLimitDmlStatements());
System.debug('After DmlRows : ' + Limits.getDmlRows());

Results in a successful completion and confirmation of no governor usage.

09:00:14.185 (5185191000)|USER_DEBUG|[1]|DEBUG|Before DmlStatements : 150

09:00:14.185 (5185303000)|USER_DEBUG|[2]|DEBUG|Before DmlRows : 0

09:00:14.185 (5185553000)|SYSTEM_CONSTRUCTOR_ENTRY|[3]|()

09:00:14.185 (5185606000)|SYSTEM_CONSTRUCTOR_EXIT|[3]|()

09:00:14.185 (5185933000)|USER_DEBUG|[4]|DEBUG|After DmlStatements : 150

09:00:14.186 (5186055000)|USER_DEBUG|[5]|DEBUG|After DmlRows : 0

Attribution
Source : Link , Question Author : Robert Sösemann , Answer Author : Community

Leave a Comment