Monday, May 27, 2013

Salesforce : APEX Class with/without sharing keyword

With or Without Sharing Keywords with APEX class  :

Generally Apex code executes in System contexts, means Access to  all objects,fields and records etc.
(beyond current users permissions, field level security or sharing settings).

(Where do I find "Sharing Settings"? its under "Setup" => "Administration Setup" => "Security Controls" => "Sharing Settings") Know More about "Salesforce Sharing Settings"

Note: ( Exception ) Anonymous code blocks always execute with current user permissions :)

So take care while developing code that user doesn't see/process data which he is not suppose to.
E.g. declaring apex class method as webservice ( take a look , kind of data you process or return inside webservice apex method ).
Give suitable access for class ( to suitable profiles) , once accessed by webservice call, then APEX executes in system context.

:) But this is also possible to execute Apex Class with current user's "Sharing settings". using "With Sharing" keyword. ( consider salesforce sharing setting while executing Apex code )

Note: "With sharing" keyword doesn't enforce the user's permissions and field-level security.


public with sharing class MyNewClassWithSharing {
// Code here

Use the without sharing keywords means sharing rules for the current user are not enforced. For example:

public without sharing class MyNewClassWithOutSharing {
// Code here

Points to be noted:
A)  If with or without sharing are not mentioned with class then default is "Without sharing".

B)  If the class is defined with NO "sharing type" and called with in other class then it will execute with calling class's sharing setting accordingly.
    Else executes with with its own settings.
B)  The sharing setting applies to all code contained with in the class, including initialization code, constructors, and methods.

C)  Classes inherit this setting from a parent class when one class extends or implements another.

D)  Inner classes do not inherit the sharing setting from their container class.

E)  Class declared as with sharing can call code that operates as without sharing

F)  All SOQL or SOSL queries that use PriceBook2 ignore the with sharing keyword

G)  Using with sharing keyword :
i) SOQL and SOSL queries, may return fewer rows
ii) DML operation may fail due to insufficient privileges for current user.


  1. Wow, awesome blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is great, let alone the content!

    PIC Scheme Singapore