You can perform DML operations either on a single sObject, or in bulk on a list of sObjects. Performing bulk DML operations is the recommended way because it helps avoid hitting governor limits, such as the DML limit of 150 statements per Apex transaction. This limit is in place to ensure fair access to shared resources in the Force.com multitenant platform. Performing a DML operation on a list of sObjects counts as one DML statement for all sObjects in the list, as opposed to one statement for each sObject.
This is an example of performing DML calls on single sObjects, which is not efficient.
The for loop iterates over contacts, and for each contact, it sets a new value for the Description__c field if the department field matches a certain value. If the list contains more than 150 items, the 151st update call returns an exception that can’t be caught for exceeding the DML statement limit of 150.
for(Contact badCon : conList) { if (badCon.Department = 'Finance') { badCon.Description__c = 'New description'; } // Not a good practice since governor limits might be hit. update badCon; }
This is a modified version of the previous example that doesn’t hit the governor limit. It bulkifies DML operations by calling update on a list of contacts. This counts as one DML statement, which is far below the limit of 150.
// List to hold the new contacts to update. List<Contact> updatedList = new List<Contact>(); for(Contact con : conList) { if (con.Department == 'Finance') { con.Description = 'New description'; // Add updated contact sObject to the list. updatedList.add(con); } } // Call update on the list of contacts. // This results in one DML call for the entire list. update updatedList;
The other governor limit that affects DML operations is the total number of 10,000 rows that can be processed by DML operations in a single transaction. All rows processed by all DML calls in the same transaction count incrementally toward this limit. For example, if you insert 100 contacts and update 50 contacts in the same transaction, your total DML processed rows are 150 and you still have 9,850 rows left (10,000 - 150).
Most DML operations execute in system context, ignoring the current user's permissions, field-level security, organization-wide defaults, position in the role hierarchy, and sharing rules. For more information, see Enforcing Sharing Rules.
Note that if you execute DML operations within an anonymous block, they will execute using the current user’s object and field-level permissions.