I am updating a value on related record based on the count of another record. The condition is say A is lookup to B record. So, if there is only one B record then certain Value of a field say C on B record will be populated to a new field in A record.
There are no conditional statements (such as
IF()) in SOQL, and you can't put an aggregate function like
WHEREclause, so you'll need to do at least some of the processing in Apex.
I don't think the Declarative Lookup Rollup Summary Tool is a fit for you in this case, because I don't know if it allows you to restrict the 'rollup' based on a count.
That aside, there are a couple of queries that can accomplish what you want.
First, using aggregate functions:
Second, using Parent-Child subquery:
In the end, there's not much of a difference between these two queries. The only appreciable difference is in the Apex to process each query.
For the first query (n.b. You'll need to manually cast the value from
For the second query:
Either one could be used in a trigger for either object, or in a separate Apex class.
If you do use this as a base for a trigger on
Object_A__c, you'd want to have this snippet execute
Before Update. You'd also want to modify the snippet to make use of
Trigger.newMapto avoid using a DML statement.