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

Restrict delete of master record if it has children

I recall something along time ago were you could stop the deleting of a record if it has children (in a master or lookup relationship).


The method used validation rules instead of a trigger. 


Anyone know how to do this?




Hi ryyh,

When creating a new lookup relationship you have an option to stop the deletion of the lookup record that's part of a lookup relationship.

Is this what you were looking for?


In this case it's a master -detail which doesn't give you that option.

There's a way to do it with i believe rollup fields & validation rules. It was in the Salesforce Developer Certification videos i saw like 5 years ago but can't find it now
Kamatchi Devi SargunanathanKamatchi Devi Sargunanathan

Hi ryyh,


Validation rule is used to check the data is correctly entered before creation of a record or updation.

So, it cannot be applied while deletion. But, You can achieve this using trigger.


Try the following trigger example,


trigger preventDeletion on Parent__c(before delete){
   for(Parent__c pa : Trigger.Old){
        Child__c chlist = [select id, parent__c from child where parent__c =:];  //list to hold child matches the parent

        if(chlist.size() > 0){

            pa.adderror('Child record is refering this record...So, you cannot delete it...!');



The above trigger will execute while you try to delete a record that has a child records exist.


Hopw this will help you...!


There's a way to do it without Triggers. That's what I'm looking for.

Hi ryyh,


Take a look at this: Useful validation formulas


This includes a validation to stop the deletion of child records, this may help (see page 26 and 27).


Hope this helps!


Subhasis SanyalSubhasis Sanyal
Using Validation Rules in conjunction with Roll-Up Summary Field to stop Child Record deletion is only possible in Master-Detail relationship. Consider the case of Account (Master) and Opportunities (Detail). Create a Roll-Up Summary Field in Account that performs a Count function for Opportunities. Every time you will go to delete an Opportunity, it will result an Update on the Account record on the aforesaid Roll-Up Summary Field. Now, you can implement a Validation Rule stop this Account record update and forcefully cancel the Opportunity deletion.
Saravanan Sivalingam 1Saravanan Sivalingam 1
Subhasis Sanyal great idea.. thanks my issue has been cleared through ur answer .once again thanks.
Neerpal SinghNeerpal Singh
trigger preventdeletion on Account (before delete) {
for (Account a:trigger.old)
    list<contact> c = [select AccountID  from contact where AccountID];
    if (c.size()>0){
        a.adderror('Account is associated with child records');

any advice witht the respective test class as well?