[SalesForce] How to update list when only specific field changes using trigger

I have a trigger which will update the field on update. But how to update only when specific field changes ?

I tried below code but it is still running when any update is made on record.

Note : in the below code I want to update listCB because if I use other list it is throwing some other system exception.

Trigger :

trigger updateTriger on Opportunity(after update) {

    List<Custom_object__c> listCB = [
        Select Id,
         Name,
         Checkbox__c,
         LookupOpp__c
        IN: trigger.newMap.keySet()];

    if(!listCB.isEmpty()) {
        for(Opportunity opp : trigger.new) {
            if(trigger.newMap.get(opp.Id).LookupCB__c != trigger.oldMap.get(opp.Id).LookupCB__c ) {

                for(Custom_object__c cb :listCB) {
                    if(cb.LookupOpp__r.LookupCB__c  != null) {
                        cb.Checkbox__c = true;
                    }
                }           
            }
        }
    }
    update listCB;
    }

Best Answer

It is updating anyway, because the line

update  listCB;

The code should be something like below:

trigger updateTriger on Opportunity(after update) {

list<Id> l_recordIdChanged = new list<Id>();
list<Opportunity> l_opp2Update = new list<Opportunity>();

for(Opportunity opp : trigger.new) {
    if(opp.LookupCB__c != trigger.oldMap.get(opp.Id).LookupCB__c ) {
        l_recordIdChanged.add(opp.id);
    }
}

for(Opportunity lookupopp : [Select Id,Name,Checkbox__c,LookupOpp__c from Opportunity where LookupOpp__c IN :l_recordIdChanged]){

    lookupopp.checkbox__c= true;
    l_opp2Update.add(lookupopp);
}


if(! l_opp2Update.isEmpty(){
    update l_opp2Update;
}
}