---
url: https://trigger.beyondthecloud.dev/before-insert/add-ons/related-query.md
description: >-
  Query children, siblings, duplicates or configuration once per handler per run
  in before insert and read them per record, without SOQL in the loop.
---

# BeforeInsert.RelatedQuery

Query children, siblings or other records once per handler per run, and read them per record with `record.getRelated(name)`.

**Signature**

```apex
public interface RelatedQuery {
    Map<String, BeforeInsert.RecordsProvider> queryRelatedOnBeforeInsert();
}
```

* `queryRelatedOnBeforeInsert()`: called at most once per handler per run, at this handler’s first `getRelated`. Returns provider name → `RecordsProvider`.

**Example**

::: code-group

```apex [Skeleton]
public with sharing class ContactPopulator implements BeforeInsert.Populator, BeforeInsert.RelatedQuery {
    public Map<String, BeforeInsert.RecordsProvider> queryRelatedOnBeforeInsert() {
        return new Map<String, BeforeInsert.RecordsProvider>{ 'accountContacts' => new AccountContactsProvider() };
    }

    public Boolean populateOnBeforeInsertWhen(TriggerTypes.InsertRecord record) {
        return record.isNotNull(Contact.AccountId);
    }

    public void populateOnBeforeInsert(TriggerTypes.InsertRecord record) {
        Id accountId = ((Contact) record.getNewSObject()).AccountId;

        record.put(Contact.Description, 'Contacts on the account: ' + record.getRelated('accountContacts').getAllWhereKeyEquals(accountId).size());
    }

    private with sharing class AccountContactsProvider implements BeforeInsert.RecordsProvider {
        public List<SObject> query(TriggerTypes.InsertRecords records) {
            return [SELECT Id, AccountId FROM Contact WHERE AccountId IN :records.getIdsOf(Contact.AccountId)];
        }

        public String keyOf(SObject row) {
            return ((Contact) row).AccountId;
        }
    }
}
```

```apex [Duplicate email]
public with sharing class ContactDuplicateEmailValidator implements BeforeInsert.Validator, BeforeInsert.RelatedQuery {
    public Map<String, BeforeInsert.RecordsProvider> queryRelatedOnBeforeInsert() {
        return new Map<String, BeforeInsert.RecordsProvider>{ 'existingContacts' => new ExistingContactsProvider() };
    }

    public Boolean addErrorOnBeforeInsertWhen(TriggerTypes.InsertRecord record) {
        Contact newContact = (Contact) record.getNewSObject();

        return record.isNotBlank(Contact.Email) && record.getRelated('existingContacts').getFirstWhereKeyEquals(newContact.Email.toLowerCase()) != null;
    }

    public void addErrorOnBeforeInsert(TriggerTypes.RejectableInsertRecord record) {
        record.addError(Contact.Email, 'A contact with this email already exists.');
    }

    private without sharing class ExistingContactsProvider implements BeforeInsert.RecordsProvider {
        public List<SObject> query(TriggerTypes.InsertRecords records) {
            return [SELECT Id, Email FROM Contact WHERE Email IN :records.getValuesOf(Contact.Email)];
        }

        public String keyOf(SObject row) {
            return ((Contact) row).Email?.toLowerCase();
        }
    }
}
```

:::

## RecordsProvider {#records-provider}

**Signature**

```apex
public interface RecordsProvider {
    List<SObject> query(TriggerTypes.InsertRecords records);
    String keyOf(SObject row);
}
```

* `query(records)`: called once per provider, at the handler’s first `getRelated` with its name, with every record in the chunk. Returns the rows to index by key; `null` counts as no rows.
* `keyOf(row)`: called once per row that `query` returned. Returns the key that `getFirstWhereKeyEquals` and `getAllWhereKeyEquals` match; `null` leaves the row out of the index.

## Rules {#rules}

* **No Ids yet.** `records.getIds()` is empty. Filter by field values with `records.getValuesOf(…)` or by lookups with `records.getIdsOf(…)`.
* **SOQL cannot see this save.** The new records are not in the database yet. Compare them with each other in a Populator's [Finalizer](/before-insert/add-ons/finalizer).
* **Keys match exactly, case included.** Normalize text keys the same way in `keyOf` and in the lookup, as `[Duplicate email]` does with `toLowerCase()`.
* **Providers query on the first read.** A provider queries when the handler first calls `getRelated` with its name. A read in a predicate queries even when nothing qualifies, so return an empty list from `query` when no record can qualify.

::: warning
Each provider has its own sharing. Declare a keyword on every provider class; an inner class does not inherit it. A `with sharing` duplicate check misses records the user cannot see.
:::
