Newer Version Available

This content describes an older version of this product. View Latest

Inserting and Updating Records

Using DML, you can insert new records and commit them to the database. Similarly, you can update the field values of existing records.

This example shows how to insert three account records and update an existing account record. First, it creates three Account sObjects and adds them to a list. It then performs a bulk insertion by inserting the list of accounts using one insert statement. Next, it queries the second account record, updates the billing city, and calls the update statement to persist the change in the database.

Inserting Related Records

You can insert records related to existing records if a relationship has already been defined between the two objects, such as a lookup or master-detail relationship. A record is associated with a related record through a foreign key ID. You can only set this foreign key ID on the master record. For example, if inserting a new contact, you can specify the contact's related account record by setting the value of the AccountId field.

This example shows how to add a contact to an account (the related record) by setting the AccountId field on the contact. Contact and Account are linked through a lookup relationship.

Updating Related Records

Fields on related records can't be updated with the same call to the DML operation and require a separate DML call. For example, if inserting a new contact, you can specify the contact's related account record by setting the value of the AccountId field. However, you can't change the account's name without updating the account itself with a separate DML call. Similarly, when updating a contact, if you also want to update the contact’s related account, you must make two DML calls. The following example updates a contact and its related account using two update statements.