Delete records across multiple objects using Apex in Salesforce

Delete records across multiple objects using Apex in Salesforce

Database.delete() can be used to delete records across multiple objects using Apex in Salesforce.

Sample Code:

List < Id > toDeleteIds = new List < Id > { 
'0WO2M000000mbwnWAA',  
'5002M00000mnEdCQAU',  
'0WO2M000000qewsWAA',  
'a0k2M000066AYgKQAW'
};    
  
Database.DeleteResult[] deleteResults = 
	Database.delete( toDeleteIds, true );  
for ( 
	Database.DeleteResult dr : 
	deleteResults 
) {     
				
	if ( !dr.isSuccess() ) {  

		for ( 
			Database.Error err : 
			dr.getErrors() 
		) {  

			System.debug(
				LoggingLevel.Error, 
				'The following error has occurred.'  
				+ '\n' + err.getStatusCode() + 
				': ' + err.getMessage() +
				'\n fields that affected this error: ' 
				+ err.getFields()
			);  

		}  

	}  

}  

Note:
Don’t include child record ids and master records ids if they are strongly coupled( Master Detail Relationship ).

Leave a Reply