0

I am trying to delete contacts that match certain conditions, using Developer console >> DEbug >> open execute anonymous window, but it throws an error

   List<Contact> contacts = [
        SELECT Id, FirstName, LastName, Email
        FROM Contact
        WHERE Email = null OR Email = ''
        LIMIT 742
    ];
    
    // To see the results before deletion, loop through the contacts and print their details
    for (Contact c : contacts) {
        System.debug('Contact Id: ' + c.Id + ', FirstName: ' + c.FirstName + ', LastName: ' + c.LastName + ', Email: ' + c.Email);
    }
    
    // Delete the contacts that meet the specified conditions
    delete contacts;

Line: 14, Column: 1 System.DmlException: Delete failed. First exception on row 0 with id 003EX0003tMiQYAU; first error: DELETE_FAILED, Your attempt to delete m***@.com could not be completed because it is associated with the following portal users.:m@***.com : []

After that, I tried the following

List<Contact> contacts = [
    SELECT Id, FirstName, LastName, Email, AccountId
    FROM Contact
    WHERE (Email = null OR Email = '')
    LIMIT 742
];

List<Contact> contactsToDelete = new List<Contact>();
List<User> usersToDeactivate = new List<User>();

for (Contact c : contacts) {
    // Query the User object to see if a portal user is associated with the Contact
    List<User> portalUsers = [SELECT Id, IsActive FROM User WHERE ContactId = :c.Id AND IsActive = true];
    
    // If an active portal user is associated with the Contact, deactivate the user
    if (!portalUsers.isEmpty()) {
        User portalUser = portalUsers[0];
        portalUser.IsActive = false;
        usersToDeactivate.add(portalUser);
        System.debug('Deactivating portal user associated with contact Id: ' + c.Id);
    }
    
    // Add the Contact to the contactsToDelete list
    contactsToDelete.add(c);
}

// Deactivate portal users
update usersToDeactivate;

// Delete the Contacts
delete contactsToDelete;

Throws error: Line: 13, Column: 1 System.LimitException: Too many SOQL queries: 101

What is the best way to delete these records.

3 Answers 3

0

Your thinking is almost correct, except you shouldn't be querying records within a loop. You can use a join in your Contact query to filter those contacts that are associated with portal users.

So it would be a query like:

SELECT Id FROM Contact WHERE [conditions to find contacts] AND Id NOT IN (SELECT ContactId FROM User WHERE IsActive = True)

So it will exclude contacts associated with those portal users. After doing that, you can deal with portal users however you want, in a separate execution (either ignoring them, deactivating them only, etc).

1

Never add SOQL inside for loop as Salesforce has governor limit of 100 SOQL statements in one transaction.

Modified your code as Below:

        List<Contact> contacts = [
            SELECT Id, FirstName, LastName, Email, AccountId
            FROM Contact
            WHERE (Email = null OR Email = '')
            LIMIT 742
        ];
        
        List<Contact> contactsToDelete = new List<Contact>();
        List<User> usersToDeactivate = new List<User>();
        
        List<User> portalUsers = [SELECT Id, IsActive FROM User WHERE ContactId IN :contacts AND IsActive = true];
        
        Map<Id,User> contactIdWithUserMap = new Map<Id,User>();
        for(User objUser : [SELECT Id, IsActive,ContactId FROM User WHERE ContactId IN :contacts AND IsActive = true]){
            contactIdWithUserMap.put(objUser.ContactId,objUser);
        }
        
        for (Contact c : contacts) {
            // If an active portal user is associated with the Contact, deactivate the user
            if(contactIdWithUserMap.containsKey(c.Id)){
                User portalUser = contactIdWithUserMap.get(c.Id);
                portalUser.IsActive = false;
                usersToDeactivate.add(portalUser);
                System.debug('Deactivating portal user associated with contact Id: ' + c.Id);
            }
            // Add the Contact to the contactsToDelete list
            contactsToDelete.add(c);
        }
        
        // Deactivate portal users
        update usersToDeactivate;
        
        // Delete the Contacts
        delete contactsToDelete;
4
  • tried but got this error -- Line: 34, Column: 1 System.DmlException: Delete failed. First exception on row 0 with id 003EX000003tMiQYAU; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): Contact, original object: User: [] Commented Mar 31, 2023 at 15:57
  • Then user & contact is not allowed to update in one transaction. First update user and then delete contact
    – whoisnilu
    Commented Mar 31, 2023 at 18:22
  • Deactivation was succesful it says but when I try to delete CONTACT it throw this error it Line: 14, Column: 1 System.DmlException: Delete failed. First exception on row 0 with id 003EX000003tMiQYAU; first error: DELETE_FAILED, Your attempt to delete m**@p.com could not be completed because it is associated with the following portal users.: m**@p.com: [] Commented Mar 31, 2023 at 19:31
  • Instead of making user inactive, have you tried making disabled portal user? portalUser.IsPortalEnabled=false
    – whoisnilu
    Commented Apr 1, 2023 at 6:28
0

The error System.LimitException: Too many SOQL queries: 101 is because you cant have more of 100 SOQL query (Synchronous limit)

(https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm)

List<Contact> contacts = [
    SELECT Id, FirstName, LastName, Email, AccountId
    FROM Contact
    WHERE (Email = null OR Email = '')
    LIMIT 742
];

List<User> usersToDisable = [select id, isActive from User where ContactId in :contacts and isActive=true];
for (User u : usersToDisable) {
  u.isActive= false;
}
update usersToDisable;

delete contacts;
1
  • Changed to 100 as well still error Commented Mar 31, 2023 at 15:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .