Very new to Apex and never touched java, basically what I am trying to do is delete all records then insert records inside multiple custom objects. Bellow is my code for just the deleting part but I have no idea how to get this working. Once I know how to get it working I can then put it inside a lop etc I just need the basics running first.

    List<String> myList = new List<String> {'More_Info_Request__c'};

    String foo = myList.get(0);

    List<More_Info_Request__c> existing = [SELECT Id From :foo ];
    delete existing;

Any help would be amazing


The code below uses a list of object names to dynamically query all the records in each object and then delete them.

List<String> objectNames = new List<String> {'More_Info_Request__c', 'Object1__c', 'Object2__c'};

for (String objectName : objectNames) {
    List<SObject> existing = Database.query('select id from ' + objectName);
    delete existing;

There are some issues with the code. Mainly that there is SOQL and a DML operation in a loop which is not advised as you will hit a governor limit pretty quickly.

  • I seem to be getting the error - Method does not exist or incorrect signature: Database.execute(String) – OliverBS Feb 20 '15 at 14:42
  • Whoops! I was writing from memory. The method should of been query(). Ive updated my answer – BarCotter Feb 20 '15 at 14:43
  • 1
    No need for a temporary variable: delete Database.query('select id from '+objectName); – sfdcfox Feb 20 '15 at 17:04

Welcome to the world of Salesforce. While team is here help you, reading through this manual would sure take you far.

Coming to this question, there are two ways you can write SOQL. Static and Dynamic.

Static soql is when Salesforce compiler knows what you are trying to do. It can detect any issues at compile time but lacks flexibility at times.

Dynamic soql is when Salesforce compiler doesn't know about the actual contents of soql you are trying to execute. So if there are any issues, you will find them out runtime but it gives you most flexibility.

Example of how to delete all records from multiple objects using dynamic soql is given by @BarCotter. As he mentioned, be aware of Salesforce Limits :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.