Delete & Update Related Records

Delete Record in Apex –

You can delete records using the delete statement.  Deleted records aren’t deleted permanently from, but they’re placed in the Recycle Bin for 15 days from where they can be restored.

Contact[] contactsDel = [SELECT Id FROM Contact WHERE LastName=’Smith’];
delete contactsDel;

Deleting Related Records – 

The delete operation supports cascading deletions. If you delete a parent object, you delete its children automatically.

Update Related records –

Fields on related records can’t be updated with the same call to the DML operation but it requires a separate DML call.

Suppose, when updating a contact, if you also want to update the contact’s related account, you must make two DML calls.

// Query for the contact, which has been associated with an account.
Contact queriedContact = [SELECT Account.Name
FROM Contact
WHERE FirstName = 'Mario' AND LastName='Ruiz'

// Update the contact's phone number
queriedContact.Phone = '(415)555-1213';

// Update the related account industry
queriedContact.Account.Industry = 'Technology';

// Make two separate calls
// 1. This call is to update the contact's phone.
update queriedContact;
// 2. This call is to update the related account's Industry field.
update queriedContact.Account;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s