Hello friends, In this tutorial, I am going to illustrate sharing keywords and there types with an example in Salesforce.

After completing this tutorial, you will able to:
  • Know the difference between “With Sharing” “Without Sharing” keywords.
  • How to use sharing keywords?
So let’s begin,

Sharing Keywords in Salesforce: 
    1. With Sharing. 
    2. Without Sharing. 
 
A major foundation of salesforce is security and these sharing keywords are an important part of this security feature. Apex script run in system context without having current user permission so triggers and web services have access to all records very easily.
            To make sure that apex classes, triggers, and web services don’t expose sensitive data to unauthorized users, we can declare an Apex script does enforce running user’s security level by using “With Sharing” keywords in our apex classes. This “With Sharing” keywords can impact your SOQL and SOSL queries as well as DML operations so be careful.
In another side “Without Sharing” keyword make sure that apex scripts don’t enforce the sharing rule of the running user.

Note: By default, an Apex class always execute in system context (Without Sharing) i.e. Apex code has access to all objects and fields irrespective of the logged in User.

In simple words:

With Sharing: Does enforce sharing rule of running user on apex script.
Without Sharing: Doesn’t enforce sharing rule on apex script.

Examples:
 public with sharing class MySharingClass{
            // implement code here
 }

 public without sharing class MyWithoutSharingClass{
            // implement code here
 }

Conclusion:
Hope you like this tutorial, for any query or suggestions please feel free to comment.
Thank you.