How can I clean up a Salesforce database by deleting all records?
I have been tasked with cleaning up a Salesforce database by deleting all records from a custom Object that is no longer needed. How can I approach this particular task for ensuring that only the records from the specific Object are deleted, without affecting other data on the Salesforce Instance?
In the context of Salesforce, you can delete all records from a custom Object in Salesforce while ensuring that only the records from the specific object are deleted, by using a combination of Salesforce object query language (SOQL) and apex code:-
Here is how you can approach this particular task:-
Identify the custom object API name
Firstly, you would need to know the AOI name of the custom object from which you want to delete the record.
Write an apex class with a method for records deletion:-
Public class DeleteRecordsController {
Public static void deleteAllCustomRecords() {
List recordsToDelete = [SELECT Id FROM CustomObject__c];
Delete recordsToDelete;
}
}
Create a Visualforce page for execution:-
If you want to implement this process of deletion by q UI, then you can create a Visualforce page with a button which can invoke the apex method:-
Implementation of the apex method
You can run the “deleteAllCustomRecords” method from the developer console or just by navigating to the Visualforce page which you have created.
Here is the example given of deleting all records from a custom object in Salesforce using apex and Visualforce in a single file:-
Public class DeleteRecordsController {
Public void deleteAllCustomRecords() {
List recordsToDelete = [SELECT Id FROM CustomObject__c];
Delete recordsToDelete;
}
}
Here is the example given in java programming language:-
Import com.sforce.soap.enterprise.DeleteResult;
Import com.sforce.soap.enterprise.EnterpriseConnection;
Import com.sforce.soap.enterprise.LoginResult;
Import com.sforce.soap.enterprise.QueryResult;
Import com.sforce.soap.enterprise.SessionHeader;
Import com.sforce.ws.ConnectorConfig;
Import com.sforce.ws.ConnectorException;
Public class SalesforceRecordDeletion {
Private static final String USERNAME = “your_username”;
Private static final String PASSWORD = “your_password”;
Private static final String SECURITY_TOKEN = “your_security_token”;
Private static final String OBJECT_API_NAME = “CustomObject__c”;
Public static void main(String[] args) {
ConnectorConfig config = new ConnectorConfig();
Config.setUsername(USERNAME);
Config.setPassword(PASSWORD + SECURITY_TOKEN);
Try {
EnterpriseConnection connection = new EnterpriseConnection(config);
LoginResult loginResult = connection.login(USERNAME, PASSWORD + SECURITY_TOKEN);
String sessionId = loginResult.getSessionId();
// Set the session header for subsequent calls
SessionHeader sessionHeader = new SessionHeader();
sessionHeader.setSessionId(sessionId);
connection.setSessionHeader(sessionHeader);
// Query all records from the custom object
QueryResult queryResult = connection.query(“SELECT Id FROM “ + OBJECT_API_NAME);
// Delete all records from the custom object
DeleteResult[] deleteResults = connection.delete(queryResult.getRecords());
// Process the deletion results if needed
For (DeleteResult result : deleteResults) {
If (result.isSuccess()) {
System.out.println(“Record deleted: “ + result.getId());
} else {
System.out.println(“Failed to delete record: “ + result.getId() + “, Error: “ + result.getErrors()[0].getMessage());
}
}
} catch (ConnectorException e) {
e.printStackTrace();
}
}
}
Here is the example given in python programming language:-
From simple_salesforce import Salesforce
From simple_salesforce.exceptions import SalesforceAuthenticationFailed
From simple_salesforce.exceptions import SalesforceMalformedRequest
# Salesforce credentials and object API name
USERNAME = ‘your_username’
PASSWORD = ‘your_password’
SECURITY_TOKEN = ‘your_security_token’
OBJECT_API_NAME = ‘CustomObject__c’
# Connect to Salesforce
Try:
Sf = Salesforce(username=USERNAME, password=PASSWORD, security_token=SECURITY_TOKEN)
Except SalesforceAuthenticationFailed:
Print(“Salesforce authentication failed. Please check your credentials.”)
Exit()
# Query all records from the custom object
Try:
Records_to_delete = sf.query_all(f”SELECT Id FROM {OBJECT_API_NAME}”)[‘records’]
Except SalesforceMalformedRequest:
Print(f”Failed to query records from {OBJECT_API_NAME}. Check the object API name.”)
Exit()
# Delete all records from the custom object
If records_to_delete:
Try:
Delete_results = sf.bulk.CustomObject__c.delete([record[‘Id’] for record in records_to_delete])
For result in delete_results:
If result[‘success’]:
Print(f”Record deleted: {result[‘id’]}”)
Else:
Print(f”Failed to delete record: {result[‘id’]}, Error: {result[‘errors’]}”)
Except Exception as e:
Print(f”An error occurred while deleting records: {e}”)
Else:
Print(f”No records found in {OBJECT_API_NAME}.”)