APEX ACCESS MODIFIERS - With Sharing • Without Sharing
APEX ACCESS MODIFIERS - With Sharing • Without Sharing
with sharing and without sharing determine how a class enforces sharing rules (such as object-level and record-level security). These modifiers do not control visibility like public or private do — they control whether record-level access is respected.APEX SHARING MODIFIERS
with sharing
-
Enforces the current user's sharing rules.
-
Only allows access to records that the user has permission to see.
-
Recommended for most business logic to respect security.
demo
without sharing
-
Ignores sharing rules (runs in system context).
-
Can access all records, regardless of user's access.
-
Use with caution, typically for admin-level operations or utilities.
Default Behavior (If Omitted)
If neither with nor without sharing is specified:
-
Default is "inherited" from the caller class if one exists.
-
If the class is run from anonymous Apex or triggers, it runs without sharing by default.
Key Notes
-
with sharingdoes not enforce object or field-level security (usestripInaccessibleorSecurity.stripInaccessible()for that). -
Triggers always run in system context (like
without sharing). -
Consider using
inherited sharing(available from API 44.0+) to inherit sharing context dynamically.
✅ Summary Table
| Modifier | Enforces Sharing Rules | Use Case |
|---|---|---|
with sharing | ✅ Yes | Most business logic |
without sharing | ❌ No | Admin tasks, internal utilities |
inherited sharing | Depends on caller | Flexible/shared utility logic |
| No modifier | Depends on context | Risky—explicit is better |
