---
url: https://trigger.beyondthecloud.dev/after-delete/add-ons/related-query.md
description: >-
  Query the records that remain after a delete, or records that still look up to
  the deleted rows, once per handler per run in an after delete handler.
---

# AfterDelete.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, AfterDelete.RecordsProvider> queryRelatedOnAfterDelete();
}
```

* `queryRelatedOnAfterDelete()`: 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 ContactWriter implements AfterDelete.Writer, AfterDelete.RelatedQuery {
    public Map<String, AfterDelete.RecordsProvider> queryRelatedOnAfterDelete() {
        return new Map<String, AfterDelete.RecordsProvider>{ 'accountContacts' => new AccountContactsProvider() };
    }

    public Boolean writeOnAfterDeleteWhen(TriggerTypes.DeleteRecord record) {
        return record.isNotNull(Contact.AccountId);
    }

    public void writeOnAfterDelete(TriggerTypes.DeleteRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        Id accountId = ((Contact) record.getOldSObject()).AccountId;
        Integer contactCount = record.getRelated('accountContacts').getAllWhereKeyEquals(accountId).size();

        unitOfWork.toInsert(new Task(WhatId = accountId, Subject = 'Contacts on the account: ' + contactCount));
    }

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

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

:::

## RecordsProvider {#records-provider}

**Signature**

```apex
public interface RecordsProvider {
    List<SObject> query(TriggerTypes.DeleteRecords 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}

* **Inbound lookups may be stale.** Records that looked up to a deleted row may still point at it during this trigger. Exclude them with `AND ReportsToId NOT IN :records.getIds()`.
* **Providers run on the first read.** A provider queries when the handler first calls `getRelated` with its name, at most once per chunk. A read in a predicate costs its SOQL even when nothing qualifies.
* **Write once per parent.** Two deleted contacts of one account both see the same remaining contacts. Write to the account once from a [Finalizer](/after-delete/add-ons/finalizer).
* **Set sharing on the provider.** Its SOQL runs under the provider class's own sharing keyword. An inner class does not inherit its outer class's keyword.

::: warning
Deleted rows are invisible. A query of the deleted object by `records.getIds()` finds nothing, with no error. Key providers by the old lookups: `records.getIdsOf(Contact.AccountId)`.
:::
