QUERY_TIMEOUT: Your query request was running for too long
What does this error mean?
Salesforce enforces a server-side query execution timeout to protect the multi-tenant platform. When a query takes too long — typically because it requires a full table scan on a large object — Salesforce terminates it and returns this error. The timeout threshold is not publicly documented but is generally triggered by non-selective queries on objects with hundreds of thousands or millions of records.
This error is different from the Apex CPU time limit — QUERY_TIMEOUT is a database-level timeout measured in wall-clock time, while CPU time is the time Apex spends in computation.
Common Causes
1. Full table scan on a large object
A query with no WHERE clause, or a WHERE clause that filters only on non-indexed fields, forces Salesforce to read every row in the table.
2. Complex WHERE clause on unindexed fields
Multiple non-indexed conditions combined with OR logic, or negation operators (!=, NOT IN), that cannot use any index and require scanning the entire table.
3. Reporting on objects with millions of records
Ad-hoc queries for reporting purposes run against production-sized data without the selective filters that operational queries use.
How to Fix It
Solution 1: Add indexed field filters
-- ❌ Full table scan
SELECT Id, Name FROM Case WHERE Custom_Category__c = 'Support'
-- ✅ Indexed fields narrow the scan
SELECT Id, Name FROM Case
WHERE CreatedDate = LAST_N_DAYS:90 -- indexed
AND OwnerId = :currentUserId -- indexed
AND Custom_Category__c = 'Support' -- now filtered on a smaller set
Solution 2: Request a custom index
If your application repeatedly filters on the same non-indexed custom field, raise a Salesforce Support case requesting a custom index. Salesforce evaluates the field's selectivity and adds the index if approved — free of charge.
Solution 3: Use Batch Apex for large-data reporting
For analytics queries that inherently need to scan large datasets, restructure as Batch Apex with Database.getQueryLocator() and process results in manageable chunks.
Pro Tip: Use the Query Plan tool in the Developer Console (Plan button in the Query Editor) to see how Salesforce would execute your query before running it in production. It shows whether an index will be used and estimates the cost.