How Can I Delete Salesforce Records with SOQL?

Photo of author
Jerome Clatworthy

Certified Salesforce Administrator

There is no SOQL command that will delete Salesforce Records.

SOQL is used to Query the Salesforce database. It can retrieve lists of records based on your criteria, and organize them in your preferred way, but SOQL cannot be used to delete Salesforce records.

SOQL can RETRIEVE Salesforce Records, but it cannot MODIFY (update/delete) Salesforce records.

KEY CONCEPT

SOQL can RETRIEVE Salesforce Records, but it cannot MODIFY (update/delete) Salesforce records.

SOQL is excellent for identifying a specific list of records that you need to modify, but you will need to take those records and perform the modification (Update/Delete) in some other way.

How to update/delete records in Salesforce if i can’t use SOQL?

Though SOQL cannot be used to modify records on its own, there are multiple ways to update records efficiently in Salesforce.

Salesforce Data Loader

You can delete Salesforce records using Data Loader, by using SOQL to export a list of record id’s into a CSV file.

Workbench

You can delete Salesforce records using Workbench, by using SOQL to export a list of record id’s into a CSV file.

Apex

You could nest a SOQL statement inside an Apex command, to delete records. For example:

List<Contact> contactsToDel = [SELECT Name FROM Contact WHERE LastName='Jones'];

if ( contactsToDel != null && !contactsToDel.isEmpty() ){
   try{
         delete contactsToDel;
  }
Catch(DmlException e){
// handle exception
}
}

Developer Console

You could use also SOQL inside the Salesforce Developer Console, for example:

delete [SELECT Name FROM Contact WHERE LastName='Jones']

References

Code snippets inspired by this forum post.