# What are the best practices for handling parent-child relationships across Batch Apex chunks?

**Topic:** Apex · **Difficulty:** Medium · **Tags:** Apex, Asynchronous Apex, Batch Apex

Read it on the site: https://www.forcechallenges.com/interview-questions/what-are-the-best-practices-for-handling-parent-child-relationships-across-batch-apex-chunks

## Answer

**Basics:** A batch chunk knows nothing about other chunks. If a parent's children are split across chunks, or a parent is processed in one transaction and its children in another, you can get partial results, duplicate work, or lock errors. The design question is which object drives the batch.

**How it works:** Pattern 1 (parent-driven): `start` returns a QueryLocator over parents; `execute` collects parent Ids, runs one query for children (`WHERE ParentId IN :parentIds`), processes them, and does one DML. Pattern 2 (child-driven): query children ordered by `ParentId`, then group by parent in `execute`. Pattern 3 (create parent and child): insert parents, then read their new Ids and insert children in the same `execute`, or relate children using an external Id reference without needing a parent Id.

**Advanced / deep dive:** Locking: updating child records locks the parent in master-detail and rolls up summary relationships, so concurrent batches or user edits on the same parent raise `UNABLE_TO_LOCK_ROW`. Mitigate by ordering the query by parent, using smaller scopes, avoiding parallel batch jobs touching the same parents, and retrying. Data skew (one parent with more than 10,000 children) makes both locking and chunk boundaries unpredictable; process such parents separately with scope 1 or a dedicated job. If you need whole-parent calculations, do not rely on children in a subquery inside `start` because subquery rows are not guaranteed to stay together across chunks; re-query children in `execute`. Cross-chunk accumulation (for example per-parent totals) needs Stateful with a bounded Map, or write intermediate results to a staging object. Always bulkify: one child query and one DML per chunk. For huge volumes consider whether a roll-up summary, Flow or CDC-based design avoids the batch entirely.

**Code / config example:**
```apex
public class ParentChildBatch implements Database.Batchable<SObject> {
    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT Id FROM Account WHERE Needs_Review__c = true ORDER BY Id');
    }
    public void execute(Database.BatchableContext bc, List<Account> scope) {
        Map<Id, Account> parents = new Map<Id, Account>(scope);
        List<Contact> toUpdate = new List<Contact>();
        for (Contact c : [SELECT Id, AccountId FROM Contact WHERE AccountId IN :parents.keySet()]) {
            c.Reviewed__c = true;
            toUpdate.add(c);
        }
        Database.update(toUpdate, false);   // partial success
    }
    public void finish(Database.BatchableContext bc) {}
}
```

**Hidden gotchas & must-remember points:**
- Chunks are separate transactions; no rollback across them.
- Parent-child DML can lock parents; expect `UNABLE_TO_LOCK_ROW` and plan retries.
- Subqueries in a QueryLocator count against the 50 million row cap of the query as a whole.
- Scope size up to 2000, default 200; lower it if each parent has many children (DML row limit 10,000 per transaction).
- Running two batch jobs over overlapping parents is a common lock source.
- Process parents with huge child counts separately.

**Best practice:** Drive from the parent, re-query children per chunk, and use small, ordered scopes with partial-success DML and logging.

---
Source: ForceChallenges · last updated 2026-11-02
