# How do you optimize SOQL queries against the AsyncApexJob object to avoid performance bottlenecks?

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

Read it on the site: https://www.forcechallenges.com/interview-questions/how-do-you-optimize-soql-queries-against-the-asyncapexjob-object-to-avoid-performance-bottlenecks

## Answer

**Basics:** `AsyncApexJob` can hold many rows in busy orgs (every batch chunk, queueable and future creates entries). A query with no filter or filtering on unselective fields scans a lot of data, slows monitoring pages and consumes SOQL query limits.

**How it works:** Filter by `Id` when you hold a job Id (fastest). Otherwise combine `JobType`, `Status` and a `CreatedDate` range, and add `ApexClassId` or `ApexClass.Name` when looking for a specific class. Always add `ORDER BY CreatedDate DESC` with a `LIMIT`. Query once per decision, and cache the answer in a variable rather than re-querying in loops.

**Advanced / deep dive:** Treat the object like any standard object for selectivity: filtering on indexed fields (the Id and standard indexed audit fields such as `CreatedDate`) is the safe route, while status flags alone are low selectivity on large tables; verify index behaviour with Query Plan in Developer Console if volume is large. Avoid selecting `ExtendedStatus` unless needed. Use `COUNT()` for capacity checks instead of fetching rows, and use aggregates (`GROUP BY Status`) for dashboards. Do not poll from Apex with repeated queries in a transaction; poll from a scheduled job at sensible intervals, from an LWC with `setInterval`, or better, react to events (`BatchApexErrorEvent`, platform events from `finish`). Remember that these queries count toward the 100 (sync) or 200 (async) SOQL limit and the 50,000 row limit. Since history is retained only for a limited time, archive important results to a custom log object and query that instead for reporting. Excluding `BatchApexWorker` children cuts noise.

**Code / config example:**
```apex
// Capacity check: how many batch jobs are active for my class?
Integer active = [
    SELECT COUNT() FROM AsyncApexJob
    WHERE JobType = 'BatchApex'
      AND ApexClass.Name = 'OppAmountBatch'
      AND Status IN ('Holding','Queued','Preparing','Processing')
      AND CreatedDate = LAST_N_DAYS:1
];

// Recent failures only, minimal fields, bounded
List<AsyncApexJob> bad = [
    SELECT Id, ApexClass.Name, Status, NumberOfErrors, ExtendedStatus, CompletedDate
    FROM AsyncApexJob
    WHERE CreatedDate = LAST_N_DAYS:3 AND NumberOfErrors > 0
    ORDER BY CreatedDate DESC
    LIMIT 100
];
```

**Hidden gotchas & must-remember points:**
- Querying by Id is always the cheapest path.
- `Status` filters alone are weakly selective on busy orgs; add a date window.
- Class-name filtering joins to `ApexClass`; use `ApexClassId` when you have it.
- Child `BatchApexWorker` rows inflate results.
- History retention is limited, so do not build audits that depend on old rows.
- Polling queries still consume SOQL limits.

**Best practice:** Filter by Id or a recent date window, limit rows and fields, and push results to your own log object for reporting.

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