Ad
Ad
Ad
Beginner Dev

Dev Tip 7: Difference between With Sharing and Without Sharing in Salesforce

Pinterest LinkedIn Tumblr

In this post, We will try to understand the key difference between With Sharing and without Sharing in Salesforce.

With Sharing Keyword: Apex by default runs in System mode or Admin mode. In Admin mode the class will have all the access to the field and object irrespective of running user’s permission. Any class that has With Sharing will enforce the Sharing rules for the current user. This has to be explicitly specified while writing the class as by default the class will have without sharing.

For Example: If a user with a Standard profile has access to Name or Address field on Account object then he/she will be able to only insert/update only Name and Address field. He/she will not be able to insert/update other fields as they do not have access to other fields as per profile access.

public with sharing class AccountsharingClass {

}

Without Sharing Keyword: Apex by default runs in without Sharing mode(ie admin mode/System mode).In Admin mode the class will have all the access to the field and object irrespective of running user’s permission. We could also explicitly specify without sharing keyword to ensure sharing rules are not imposed for the current user.

public without sharing class AccountsharingClass {

}

Note: If a method is defined in a class declared with with sharing is called

by a class declared with without sharing, the method executes with sharing 

rules are enforced. Ex: Lets assume we have two classes,Class A is created with

 “with sharing” and Class B iscreated with “without sharing”. If We call class A

from Class B then with sharing rules will be applied.

Write A Comment