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.