+ Start a Discussion

How to In account count the contacts with triggers

trigger ConCount on Account (After Update) {

    for(Account a:trigger.new)
        list<Contact> lscon = [Select id from Contact where accountid=:a.id];
        update lscon;


Your code is correct but if you use data loader or any other tool to update more than 10 Accounts at a time then your trigger will fail since the loop in your code would query more than 10 times.

You should collect the Account IDs first and then use them to query only once to get All the related contacts. Something like this below

Map<Id,Integer> acctIdMap = new Map<Id,Integer>();
for(Account a:Trigger.New) {
List<Contact> conts = [Select Id,Name from Contact where AccountId IN :acctIdMap.keyValue() ORDER BY AccountID LIMIT 49999];

Integer i = 0;
while(i<conts.size() ) {
Integer x = 0;
x = acctIdMap.get(conts.get(i).AccountId)+1;


[Do mark this answer as solution if it works for you and give a kudos.]