with sharing and without sharing

Class with sharing and without sharing in Salesforce


With Sharinguser mode execution - to enforce the sharing rules that apply to the current user.
Without Sharing
system mode execution - to ensure that the sharing rules for the current user are not enforced.

 Apex code runs in system context. In system context, Apex code has access to all objects and fields— object permissions, field-level security, sharing rules aren’t applied for the current user. This is to ensure that code won’t fail to run because of hidden fields or objects for a user.
executeAnonymous always executes using the full permissions of the current user.

If a class is not declared as either with or without sharing, the current sharing rules remain in effect. This means that if the class is called by a class that has sharing enforced, then sharing is enforced for the called class. 

Default is without sharing (System mode). 

NOTE
Although custom controllers and controller extension classes execute in system mode and thereby ignore user permissions and field-level security, you can choose whether they respect a user's organization-wide defaults, role hierarchy, and sharing rules by using the with sharing keywords in the class definition.

Comments