---
schema_version: "1"
id: 5ccde6c502a4b0617c2005718b8a3e9bf6494566d1c9b41854ff9259d539006f
title: "ApexGuru Antipattern: Redundant SOQL"
collection: admin
version: current
locale: en-us
portal_url: https://docs.salesforce.com/admin/current/en-us/xcloud/264-0-0/apexguru_antipattern_redundant_soql.md
canonical_url: https://help.salesforce.com/s/articleView?id=xcloud.apexguru_antipattern_redundant_soql.htm&release=264.0.0&type=5
source_site: help.salesforce.com
content_type: documentation
content_hash: aebfbe25c66eeaa8e270de962c4626cf7e44907493a58741de6202d33616cde5
description: Executing multiple SOQL queries on the same sObject with identical or nearly identical filter conditions creates inefficiencies. This practice wastes governor limits and increases transaction time because it requires more database round-trips. Processing separate query responses wastes CPU time and heap space.
products:
  - Cross Cloud
release: "264"
---
# ApexGuru Antipattern: Redundant SOQL

Executing multiple SOQL queries on the same sObject with identical or nearly identical filter conditions creates inefficiencies. This practice wastes governor limits and increases transaction time because it requires more database round-trips. Processing separate query responses wastes CPU time and heap space.

## Scope

Detection and recommendation

## Detection Example

```java
//Apex
// Bad: Two round-trips to the database
User userA = [SELECT Id FROM User WHERE ContactId = :idA];
User userB = [SELECT Id FROM User WHERE ContactId = :idB];
```

## Recommendation

Merge these queries into fewer SOQL statements, followed by in-memory filtering in Apex. Query all records at the same time and map them for easy access. This scales regardless of whether you need 2 records or 200.

```java
//Apex
// Good: One round-trip using a Set and Map
Set<Id> contactIds = new Set<Id>{ idA, idB };
// 1. Bulk Query
List<User> users = [SELECT Id, ContactId FROM User WHERE ContactId IN :contactIds];
// 2. In-Memory Organization (The Map Pattern)
Map<Id, User> userMap = new Map<Id, User>();
for(User u : users) {
    userMap.put(u.ContactId, u);
}
// 3. Retrieve efficiently
User userA = userMap.get(idA);
User userB = userMap.get(idB);
```