I am creating a batch apex that takes some objects and move them to a new custom object before deleting them. I also need to delete other objects connected to the first one, therefore I would need to do 2 queries in the execute method.

This is an example of what I did:

public batch() {

    query = 'SELECT Id, (SELECT Id FROM Other_Object_to_delete__r) FROM Object_to_delete WHERE flag = true';

public void execute(SchedulableContext sc) {
    Database.executeBatch(this, 100);

public Database.QueryLocator start(Database.BatchableContext bc) {
    return Database.getQueryLocator(query);

public void execute(Database.BatchableContext bc, List<sObject> scope) {
    List<New_object> newobject = new List<New_object>();
    for (SObject s: scope) {
        //working scope and create the newobject


    List<Other_Object_to_delete__2> obj2 = [SELECT Id FROM Other_Object_to_delete__2 WHERE related_object.flag = true];
    List<Other_Object_to_delete__3> obj3 = [SELECT Id FROM Other_Object_to_delete__3 WHERE related_object.flag = true];

    insert newobject;
    delete scope;

    delete obj2;
    delete obj3;

public void finish(Database.BatchableContext bc) {


How bad is it if I do this? Is it possible to query and delete objects even in the execute method?

1 Answer 1


Querying and deleting objects in the execute method should not be a problem. You're doing this outside of the for loop, so you won't come close to the limit on queries.

If the objects that you're deleting are detail objects in a master-detail relationship, they'll be deleted automatically. If they're just related, you'll need to do what you have done here.

Edited to add I just notice that your code does not include "implements Database.Batchable" on the first line, so it probably isn't running as a batch job. More details on batch code with example can be found here

As Tony Danza notes below, you can use database.emptyRecyclebin() to remove records from the recycle bin when you know there's no need to keep them. You can remove up to 10,000 per call. More details here

  • 1
    @tonydanza ... and ... sometimes it is best practice to call database.emptyRecycleBin(..) so as not to fill up the org's recyclebin with mass deletes that you aren't planning on recovering
    – cropredy
    Mar 13, 2015 at 1:41
  • yeah i deleted the implements database.batchable part when renaming the batch, but it does indeed implement it. @crop1645 should i call that method in the finish method? thanks anyway. I will probably use these two more queries.
    – tonydanza
    Mar 13, 2015 at 8:38
  • 1
    do the emptyRecycleBin() in the execute() as once the execute() completes for a given scope; the transaction is committed
    – cropredy
    Mar 13, 2015 at 20:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .