In Apex, you can use the delete statement to remove records of a custom object from the Salesforce database.
Deleting records is a common operation when you want to remove unnecessary or outdated data.
Here's an example of how to use the delete statement to delete a record from a custom object:
// Query an existing Custom Object record to delete
Custom_Object__c recordToDelete = [SELECT Id FROM Custom_Object__c WHERE Name__c = 'Record to Delete' LIMIT 1];
// Use the delete statement to remove the record
delete recordToDelete;
We first query an existing record of the custom object "Custom_Object__c" based on a specified condition using SOQL.
We retrieve the existing record into the recordToDelete variable.
We use the delete statement to remove the recordToDelete from the Salesforce database.
When you use the delete statement, the specified record is permanently removed from the database, and it cannot be recovered. Make sure you exercise caution when using the delete statement, especially in production environments.
You can also use the delete statement to delete multiple records at once by passing a list of records to be deleted. Here's an example:
List<Custom_Object__c> recordsToDelete = [SELECT Id FROM Custom_Object__c WHERE Status__c = 'Archived'];
delete recordsToDelete;
In this example, we query a list of custom object records and then use the delete statement to remove all records in the recordsToDelete list.