function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SF API 9SF API 9 

Non-Selective Query Help

I am trying to link a custom objects with a contact when custom fields on both objects match. I keep getting a non-selective query error but I ran a report and there are on 14k contacts where the custom field is not null. I thought the trigger below would prevent the trigger from running through null records. Can anyone help? 
trigger LinkContacttoOrder on Addy_Orders__c (before update) {

    Set<String> ords = new Set<String>();
    for (Addy_Orders__c o : trigger.new) ords.add(o.Addy_User_Id__c );

    Map<String, Contact> cons = new Map<String, Contact>();
    for (Contact a : [
        SELECT Addy_User_Id__c FROM Contact
        WHERE Addy_User_Id__c IN :ords And Addy_User_Id__c!=null LIMIT 1
    ]) cons.put(a.Addy_User_Id__c , a);

       for (Addy_Orders__c o : Trigger.new)
    {
        Contact Con = cons.get(o.Addy_User_Id__c );
       Id parentId = (Con == null) ? null : Con.Id;
        o.Contact__c = parentId;
    }
}

Essentially, I just want the [Contact__c] field on Addy_Orders__c to be populated with the Contact.Id IF Contact.Addy_User_Id__c = Addy_Orders__c.Addy_User_Id__c. 
Ajay K DubediAjay K Dubedi
Hi,

* Please use below code it works fine:
trigger LinkContacttoOrder on Addy_Orders__c (before update)
{
    Set<String> ords = new Set<String>();
    for (Addy_Orders__c o : trigger.new) 
    {  
        if(o.Addy_User_Id__c != NULL)
        {
            ords.add(o.Addy_User_Id__c );
        }
    }
    Map<String, Contact> cons = new Map<String, Contact>();
    for (Contact a : [SELECT Addy_User_Id__c FROM Contact WHERE Addy_User_Id__c IN :ords])
    {
        cons.put(a.Addy_User_Id__c, a);
    }
    for (Addy_Orders__c o : Trigger.new)
    {
        Contact Con = cons.get(o.Addy_User_Id__c );
        Id parentId = (Con == null) ? null : Con.Id;
        o.Contact__c = parentId;
    }
}

 
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com