This course is currently a work in progress. Please join the waitlist to receive regular updates.

Insert a collection in apex

In order to perform DML operation in apex, it is always recommended to insert a collection than individual records.

Inserting a collection of records in a single operation helps save DML governor limits within the same transaction. A transaction can trigger multiple database updates, which consume many more DML resources during the transaction.

Let's assume you've a trigger on case and account. The case trigger updates account and account trigger updates all related contacts. While running any updates on case, it will update account and then contacts.

The DML usage in apex is calculated for the whole transaction and if the DML operations are not bulkified, it will results in a governor limit exception.

Sample execution flow

Update list of case records

Trigger executed on related account records

Trigger executed on related contact records

Here is an example of inserting a collection of account records using the insert statement.

Loading...

In the above example:

  • The variable allAccounts is a list collection of type Account.
  • The variable accountRec is will contain instances of accounts.
  • The list method add() is used to add new account instances to the list collection.
  • The DML Insert method is used to insert accounts to the database.

Try It Yourself

Loading...