I have two queries, each populate a list of Cases, I need to create a third query that gets me the cases with their ID in the first query but exclude them if they are in the second query.
Example:
The requirement is for me to delete cases and the account associated with that case after 30 days if the account doesn't have a case that has been modified in the past 30 days. If the account has a case that has been modified in the past 30 days then exclude it and the cases from the delete process.
Date d = System.today() - 30;
List<Case> oldCases = new List<Case>();
oldCases = [SELECT Id, Account.Name, LastModifiedDate FROM Case
WHERE LastModifiedDate < :d
And Guest_Name__c Like '%Test%'];
//Add account id's to a list so we can compare them
Set<String> accountId = new Set<String>();
for(Case c : childCases){
accountId.add(c.AccountId);
}
List<Account> testAccounts = new List<Account>();
//Get all the accounts that had cases from the above query
testAccounts = [SELECT Id, FirstName, LastName, Account.Name FROM Account
WHERE Id IN :accountId];
List<Case> ineligibleCases = new List<Case>();
//Get all the cases on the account that have been modified in the past 30 days
ineligibleCases = [SELECT Id, Guest_Name__c, AccountId, LastModifiedDate FROM Case
WHERE AccountId In :testAccounts
AND LastModifiedDate > :d];
List<Case> casesToDelete = new List<Case>();
//Get cases that don't have tickets that have been modified in the past 30 days
casesToDelete = [SELECT Id, AccountId FROM Case
WHERE Id IN :oldCases
AND Id NOT IN :ineligibleCases];
This is where I am having trouble, the above query returns all of the cases from the first case query called oldCases, it doesn't seem to be excluding the cases from the ineligible case query. If I have 2000 cases returned from the oldCases query this query also returns 2000 cases even though the ineligibleCases query returns me 22 rows. Is this properly SOQL syntax or am I missing something?
Set<String> accountDelete = new Set<String>();
for(Case cas : casesToDelete){
accountDelete.add(cas.AccountId);
}
List<Account> accountsToDelete = new List<Account>();
//Get accounts to delete
accountsToDelete = [SELECT Id FROM Account WHERE Id IN :accountDelete];
for(Case c: casesToDelete){
system.debug('Cases to delete: ' + c);
}
for(Account a: accountsToDelete){
system.debug('Accounts to delete: ' + a);
}