With Sharing & Without Sharing

By Default Apex Class runs on System Mode

With Sharing :

  • When you want your class to enforce sharing rules of the current user before executing the code it contaions, you can use with sharing context.
  • Use this mode as default mode as this is a safe way to write code.

Without Sharing:

  • When you want your class to run and provide access irrespective of the sharing rules of the current user, you can use without sharing context.
  • This is not safe as it opens up access to unnecessary records that the current user should not be shown.
  • You can use tis for community users who need access to the records.

Apex Triggers run in without Sharing Context, as they cant be given explict sharing declaration