Intermediate 20 min read

Using the Limits Class

By the end of this lesson, you'll be able to:

  • Check how many queries or DML statements have been used so far in the current transaction
  • Use Limits methods to guard against approaching a limit dynamically
  • Explain when checking limits at runtime is genuinely useful

Prerequisites: "Bulkification Patterns"

Checking usage so far

System.debug('Queries used: ' + Limits.getQueries() + ' / ' + Limits.getLimitQueries());
System.debug('DML used: ' + Limits.getDmlStatements() + ' / ' + Limits.getLimitDmlStatements());

Limits.getQueries() and Limits.getDmlStatements() report how many have actually run so far in the current transaction; Limits.getLimitQueries() and Limits.getLimitDmlStatements() report the actual ceiling — useful for confirming, during development, that bulkified code really is staying well within limits.

Guarding dynamically before a risky operation

public void processInBatches(List<Account> accounts) {
    for (Account acc : accounts) {
        if (Limits.getQueries() >= Limits.getLimitQueries() - 5) {
            System.debug('Approaching query limit — stopping early.');
            break;
        }
        // ... some operation that queries related data ...
    }
}

This checks remaining query budget before each iteration that might consume more of it, stopping gracefully with a warning rather than crashing with a LimitException partway through — genuinely useful when a method's query count depends on data that can't be predicted in advance.

When this is actually worth reaching for

For well-bulkified code following this module's patterns, checking Limits methods is rarely necessary — the whole point of bulkification is staying comfortably under every limit regardless of data volume. Limits methods earn their keep specifically in complex, genuinely unpredictable scenarios (like Module 24's future recursive-trigger discussions, or processing that legitimately varies its query count based on incoming data) where confirming "how much room is actually left" adds real value.

Exercise

Write a line of code that debugs the current DML statement usage as a fraction, like "12 / 150".

Show hint

Limits.getDmlStatements() + ' / ' + Limits.getLimitDmlStatements()

APEX

Using the Limits Class Quiz

1. What does Limits.getQueries() return?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

The Limits class reports exactly how much of each governor limit the current transaction has already used — useful for genuinely dynamic, data-volume-dependent logic.