When to use with sharing or without sharing?

If not declared explicitly, classes are always With Sharing.

It is important to understand that in both cases (With or Without Sharing), Apex runs in System Mode, so it wouldn't respect things like Field Level Security.

Use With Sharing when the User has access to the records being updated via Role, Sharing Rules, Sales Teams - any sort of sharing really.

Without Sharing is reserved for cases where the User does not have access to the records, but there is a need to update them based on user input.

Also the With / Without Sharing commutes and if a class doesn't have an explicit declaration, the sharing context of the calling class is inherited.


Go through following link for more detailed explanation..

http://knowsalesforce.blogspot.com/2014/02/salesforce-system-mode-user-mode-and.html?spref=fb

This blog explains how with sharing and without sharing works in context of system and user mode.

Conclusion out of this blog is,

  1. In Salesforce, all apex code run in system mode. It ignores user's permissions. Only exception is anonymous blocks like developer console and standard controllers. Even runAs() method doesn't enforce user permissions or field-level permissions, it only enforces record sharing.

  2. Keywords 'With Sharing & Without Sharing' themselves suggests that they have nothing to do with permissions on object & fields. They only play role in selecting records on sharing basis.


Use the with sharing keyword when declaring a class to enforce the sharing rules that apply to the current user and if you don't want to enforce it use without sharing keyword.

We can use it in any type of classes build in apex.

If you leave it out i.e. 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.

Tags:

Sharing

Apex