Bye data!!
You're probably picking up on the pattern by now. To delete sObjects records from the database, we'll need to use the delete
DML statement. The sObject(s) you attempt to delete must have their Id attribute set.
Say you're asked to delete all Opportunities that are "Closed Lost":
List<Opportunity> oppsToDelete = [SELECT Id FROM Opportunity WHERE StageName = 'Closed Lost']; delete oppsToDelete;
This operation will delete every opportunity record pulled in by the SOQL query.
You can write the shorthand version of that code by passing the SOQL query as an argument to the DML statement:
delete [SELECT Id FROM Opportunity WHERE StageName = 'Closed Lost'];
In this case, the SOQL returns a list of sObjects, there's no need to store it in a variable before passing it to the DML statement. If you like how that looks, consider yourself the next Tiger Woods.
Recycle Bin
These records aren't permanently deleted from Salesforce. They're placed in the Recycle Bin for 15 days, where they can be restored if needed.
Cascading Deletes
Deletes can cause cascading deletes. That is, when a parent is deleted, the child records are deleted.
Say we have a child Contact record and a hypothetical child CustomObject__c record related to Account via a lookup field. Although an Account may have other child records, these two examples will help demonstrate the point.
When a delete DML statement is issued against an Account with a Contact record and a CustomObject__c record linked to it, the deletion affects the records differently. The Account and its child Contact record will be deleted, but the CustomObject__c record will not be deleted.
So make sure any child sObject records are properly reparented before deleting.
The Salesforce Docs point out that cascade-deletes bypass sharing and security settings. So they don't happen by default with Lookup relationships, but they can be enabled.
Another thing that makes this a bit tricky is that in the scenario above, the Account's delete triggers and flow will run - but the Contact's delete trigger and flows won't run. If you need to process the child records, you must do that before deleting the parent.