With sharing:
We use the keyword "with sharing" before declaring class so as to take into account the sharing rules for the user. By default apex class runs into system mode so as to avoid code failure because of permissions.
POINTS TO NOTE:
- If we do not declare class with "With sharing" or "Without sharing" the class will not take into account the sharing rules but if this class is called from another class which is declared with "with sharing" it will take into account the sharing rules.
- If the class with "with sharing" is calling method of another class with "without sharing" than the method inside "without sharing" class will execute without sharing rules.
- If the class with "without sharing" is calling method of another class with "with sharing" than the method inside "with sharing" class will execute with sharing rules.
- Inner class do not have sharing settings of parent class.
- Class have sharing settings of parent class when we implements it or extends it from parent class.
3) Let’s say an Apex class, which is not declared with any keywords such as "with sharing" or "without sharing," is fetching Opportunity records. The user running under whose context this apex class is invoked does not own any Opportunity records, nor are any Opportunity records shared with them. In this case, will the class be able to fetch Opportunity records?
with sharing nor without sharing keywords are specified), it bypasses the user's record-level access and CRUD permissions. As a result, the class can retrieve all Opportunity records, regardless of the user's permissions or whether the records are shared with them.4) Let’s say an Apex class, which is declared with the "with sharing" keyword, is fetching Opportunity records. The user, under whose context this Apex class is invoked, does not own any Opportunity records, nor are any Opportunity records shared with them. In this case, will the class be able to fetch Opportunity records?
No, the class will not be able to fetch Opportunity records. The with sharing keyword enforces sharing rules, meaning that only records the user has access to (based on sharing rules, ownership, or explicit sharing) will be retrieved. Since the user does not own any Opportunity records, nor are any records shared with them, the class will not be able to access those records.
🚀 Looking to sharpen your Salesforce skills and ace your next interview? Click below to launch the right course for you:
🎓 Full Courses:
💼 Interview-Focused Courses:

