Sub topic 15
with sharing, without sharing, and inherited sharing
This chapter assumes you can write and call Apex classes, including static methods, and that you know Salesforce records are shared with users through ownership, the role hierarchy, sharing rules, and manual shares. It covers the three sharing keywords for classes and how a class's sharing mode is decided at run time. It also covers what the keywords do not control.
What the keywords control
Apex normally runs in system context. Your code can read and write records the current user could never open in the UI, because object permissions, field-level security, and record sharing are not applied by default.
A sharing keyword changes only one of those layers: record-level sharing. In a class that enforces sharing:
- SOQL and SOSL return only the records the running user can see.
- DML on records the user cannot edit fails with an
INSUFFICIENT_ACCESS_OR_READONLYerror.
The keywords are written in the class declaration, after the access modifier:
public with sharing class OrderService { }
public without sharing class SystemJobs { }
public inherited sharing class RecordLoader { }| Keyword | Record sharing | Typical use |
|---|---|---|
| `with sharing` | Enforced for the running user | Controllers, services that act on behalf of a user |
| `without sharing` | Not enforced | Narrow system tasks, such as a rollup that must see every record |
| `inherited sharing` | Taken from the caller. Enforced when the class is an entry point | Reusable utilities and selector classes |
| (none) | Taken from the caller. Not enforced when the class is an entry point | Avoid; declare a keyword instead |
A class that declares no keyword behaves in a way that surprises many developers. When another class calls it, it runs in the caller's mode. When it is the entry point of a transaction, it runs without sharing. For example, an entry point could be a Visualforce or Aura controller, a REST resource, or a batch job. Code that reads the same in review can behave differently depending on who called it.
Without sharing is not the same as no security
Sharing keywords do not enforce object permissions (CRUD) or field-level security (FLS). A with sharing class can still query a field the user is not allowed to see, as long as the user can see the record.
To enforce CRUD and FLS, use one of these:
WITH USER_MODEin SOQL.AccessLevel.USER_MODEinDatabasemethods.Security.stripInaccessible().
User mode enforces object permissions, field-level security, and sharing together, whatever the class keyword says. WITH SECURITY_ENFORCED is an older option that checks only object and field access.
public with sharing class AccountReader {
public static List<Account> readNames() {
// Sharing: enforced by the class keyword.
// CRUD and FLS: enforced by WITH USER_MODE.
return [SELECT Id, Name FROM Account WITH USER_MODE LIMIT 50];
}
}Treat the class keyword and the query mode as two separate decisions.
How the mode is decided
Sharing is resolved for each method call, not once per transaction. The rules are:
- A class that declares
with sharingorwithout sharinguses that mode for its own code. This holds even when another class calls it. - A class that declares
inherited sharinguses the mode of its caller. If it is the entry point, it useswith sharing. - A class with no keyword uses the caller's mode. If it is the entry point, it runs without sharing.
- A class that extends or implements another class and declares no keyword inherits the parent's setting.
- An inner class does not inherit the setting of its outer class.
Rule 1 means sharing can be dropped partway through a call chain. If a with sharing method calls a without sharing method, that inner method runs without sharing. When it returns, execution is back in with sharing.
The block above is not a valid diagram. The correct diagram follows.
Worked example: mixing modes on purpose
A service acts for the user but needs one count that spans every record. The count is isolated in a small without sharing class so the rest of the code stays safe.
public with sharing class AccountService {
// Runs with sharing: the user sees only their accounts.
public static List<Account> myAccounts() {
return [SELECT Id, Name FROM Account WITH USER_MODE];
}
// Delegates to a class that deliberately ignores sharing.
public static Integer totalAccountsInOrg() {
return AccountCounter.countAll();
}
}
public without sharing class AccountCounter {
// Returns only a number, never record data.
public static Integer countAll() {
return [SELECT COUNT() FROM Account];
}
}totalAccountsInOrg() returns a number the user could not compute from visible records alone. The class exposes only an aggregate, so no record data leaks. That is the pattern to aim for. Keep the without sharing code small, give it a clear name, and make it return the least data it can.
Inherited sharing for reusable code
A selector or helper class used from many places should not decide its sharing mode. If it says with sharing, a system job that needs every record cannot use it. If it says without sharing, a user-facing controller can leak data through it. inherited sharing leaves the decision to the caller.
public inherited sharing class AccountSelector {
public static List<Account> byIds(Set<Id> ids) {
return [SELECT Id, Name FROM Account WHERE Id IN :ids];
}
}
public with sharing class AccountController {
public static List<Account> load(Set<Id> ids) {
// AccountSelector runs with sharing here, because its caller does.
return AccountSelector.byIds(ids);
}
}
public without sharing class NightlyRollup {
public static List<Account> load(Set<Id> ids) {
// The same selector runs without sharing here.
return AccountSelector.byIds(ids);
}
}The same code takes a different mode depending on who calls it. When AccountSelector is the entry point itself, it runs with sharing, which is the safe default. That default is the difference between inherited sharing and having no keyword.
Inner classes, inheritance, and tests
Inner classes do not take the setting from the class that contains them. An inner class that needs a specific mode must declare it:
public with sharing class ReportBuilder {
// Declared explicitly; it does not inherit "with sharing" from ReportBuilder.
private without sharing class OrgTotals {
public Integer accounts() {
return [SELECT COUNT() FROM Account];
}
}
public Integer totalAccounts() {
return new OrgTotals().accounts();
}
}Subclasses behave the other way. If Child extends Parent and Child declares no keyword, it takes Parent's setting. If you want a different mode, declare it on the subclass. Interfaces have no sharing keyword, because they contain no executable code.
In tests, test methods run in system context. A class under test still applies its own keyword. To check what a particular user can see, wrap the call in System.runAs(user), which supplies the running user for sharing checks.
Common mistakes
- Leaving the keyword off. The class then behaves differently as an entry point than when called by another class. Always declare one.
- Assuming
with sharingsecures fields. It does not. Pair it withWITH USER_MODEorstripInaccessible. - Using
without sharingfor convenience. Keep it for a specific need and document the reason in a comment. - Expecting an outer class's keyword to cover inner classes. It does not.
- Putting
with sharingon a shared utility. Callers that legitimately need all records then fail. Preferinherited sharing. - Forgetting that the mode changes at each call. A
with sharingclass that calls awithout sharingclass loses enforcement for that call.
Exercise
A class named PriceLookup is called from a with sharing controller and also from a without sharing batch job. It is a stateless helper that runs SOQL. Which keyword should it declare, and what happens if it is invoked directly as an entry point?
Show answer
Declare inherited sharing. Called from the controller it enforces sharing, and called from the batch job it does not, because each caller's mode is used. If it is invoked directly as an entry point, inherited sharing makes it run with sharing, which is the safe default. With no keyword it would run without sharing in that case.
Exercise
A with sharing class runs [SELECT Id, Salary__c FROM Employee__c] and the user lacks field-level security on Salary__c. Does the sharing keyword block access to the field? What would you change?
Show answer
No. The keyword controls only which records are visible, not field access. Add WITH USER_MODE to the query, or run the results through Security.stripInaccessible, so field-level security and object permissions are enforced as well.