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
chandrashekar Jangitichandrashekar Jangiti 

Hi All..delete record based on conditions

Hi All..
Could you please give sample code for
delete record based on conditions like if >0 delete record and >1 should not delete..
Ajay K DubediAjay K Dubedi
Hi Chandrashekar,

As your requirement, I understood, you want a condition to delete a record if the number is between 0 and 1.
1. For deletion, the number should be greater than 0 but not greater than 1. It may be 1 also for deletion action.
2. Restriction for deletion, the number should be greater than 1.

Example-
List<contact> contactList = [select id, name from contact limit 10];
    Integer countNumber = contactList.size();


//check the condition for deletion.
    if(countNumber >0 && countNumber <=1)
  {
    delete contactList;

   }

//In else part, check for restriction for deletion or doing anything else
 else if(countnumber > 1)
{
   system.debug('contact list - > '+ contactList);

}


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
chandrashekar Jangitichandrashekar Jangiti
Lets example Account ,Contact,AccCont_Junction__c(junction)

So here we can say 2 Accounts(Account1,Account2) and those 2 Accounts related to one Contact and here two junction objects which related to Account1-t0-Contact(AccCont_Junction__c1) ,
Account2-to-Contact(AccCont_Junction__c2) ,
-->here whenever delete Acount1 should not delete Contact and Account1-t0-Contact(AccCont_Junction__c1) would be deleted

-->Delete Account1 &Account2 then Contact will be deleted
Deepali KulshresthaDeepali Kulshrestha
Hi Chandrashekar,

I have gone through your question. According to your question, the record equal to one should be deleted. 
For that query all records in the list. The check size of the list if record size equal to the delete record.

Code ==>


List<Account>  aclist = [Select Id from Account];
if(aclist.size() == 1){
    System.debug('Delete Record--->'+aclist);
    delete aclist;
}
else
{
    System.debug('Record is greater than 1 Not Deleted');
}


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

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com