How do you optimize a SOQL query that is hitting governor limits with large data

When a SOQL query hits governor limits (like 50,000 record limit or too many queries in one transaction), you need to optimize it. Here are some strategies:

Ways to Optimize SOQL Queries

1. Use Selective Queries (Filters)

  • Add WHERE conditions that make the query selective.
// BAD Practice
SELECT Id, Name FROM Contact

// GOOD (Selective)
SELECT Id, Name FROM Contact WHERE AccountId = :accountId

2. Use LIMIT & ORDER BY –

Always limit the number of records if you don’t need all.

SELECT Id, Name FROM Opportunity WHERE StageName = 'Closed Won' ORDER BY CloseDate DESC LIMIT 100

3. Use SOQL For Loop Instead of List Query –

SOQL for processes records in batches of 200 – avoids heap size issues.

// BAD
List<Contact> cons = [SELECT Id, Name FROM Contact];
for(Contact c : cons) {
   // logic
}

// GOOD
for(Contact c : [SELECT Id, Name FROM Contact]) {
   // logic
}

4. Use Relationships Instead of Multiple Queries –

Fetch child/parent records in one query.

// Instead of querying Account and then Contacts separately
SELECT Id, Name, (SELECT Id, LastName FROM Contacts) FROM Account WHERE Id = :accId

SOQL optimization means being selective, efficient, and scalable. Use filters, fetch only what you need, and process data in chunks. This way, your queries run faster, avoid governor limits, and stay ready for future growth.