Imagine a Custom SObject X with a lookup field for Custom SObject Y. Y has an external ID field EID. As described in this answer, I can create a record X like this:
Y y = new Y(EID = 1);
X x = new X(Y__r = y);
insert x;
However, this fails if no Y record with EID = 1 exists.
To prevent this failure we could create a set of all external ids:
Set<Decimal> externalIds = new Set<Decimal>();
List<Y> ys = [SELECT EID FROM Y];
for (Y y : ys) {
externalIds.add(y.EID);
}
X x = new X();
if (externalIds.contains(1)) {
Y y = new Y(EID = 1);
x.Y__r = y;
}
insert x;
However, this won't scale. If you have e.g. 500,000 Y records, you could never create this set.
Also, the solution has to scale for thousands of records of X, so directly querying the given EID won't work either.
Is there a way to directly bind X to Y if and only if a record of Y exists that has the given EID?