Sub topic 5
without sharing: bypassing record-level sharing on purpose
This chapter assumes you know basic Apex syntax and SOQL. It also assumes you know how organization-wide defaults, roles, and sharing rules decide which records a user can see. Earlier chapters showed that Apex runs in system context by default and that with sharing applies the running user's record access. This chapter covers the opposite keyword: what without sharing does, when it is justified, and how to contain it.
What the keyword does
A class declared without sharing does not apply the running user's record-level sharing to its SOQL queries and DML. Queries can return records the user cannot see, and DML can touch records the user cannot edit.
public without sharing class AccountAdminReader {
public static List<Account> getAllAccounts() {
// Ignores record-level sharing for the running user
return [SELECT Id, Name FROM Account];
}
}If a user with a private Account model calls getAllAccounts(), the result includes every Account in the org, not only the ones that user owns or has been granted access to.
Two points need precision:
- The keyword removes only the record-level filter. It does not turn on or turn off object permissions or field-level security. Those are separate, as a later chapter explains.
- The keyword is explicit. Declaring
without sharingstates that the class's author decided to bypass the user's record access. A class with no keyword behaves differently in some call chains, and the next chapter covers that.
Why a class might need it
Record-level sharing is designed around what a person is allowed to see. Some features need a result based on data the person cannot see. Common cases:
- Aggregates for a public view. A community page shows "open cases in your region" as a number, but the user can only see their own cases.
- Uniqueness and duplicate checks. Code must confirm that no other record, including ones owned by other users, already uses a given external ID.
- System-driven maintenance. A service reassigns records or writes to a record owned by someone else, such as stamping a parent record or updating a rollup owned by a queue.
- Cross-team lookups. A sales user selects a support contact from a list. The contact record is private by sharing, but the list must be complete.
In each case the code exposes an outcome, not the raw records. That distinction guides the design rules below.
Worked example: a count the user cannot compute alone
The following class returns how many open Cases exist for an Account. The caller may see only some of those Cases, but the product requirement is to show the total.
public without sharing class OpenCaseCounter {
// Intentionally without sharing: the UI shows a total that includes
// Cases the current user cannot open. Only a number leaves this class.
public static Integer countOpenForAccount(Id accountId) {
return [
SELECT COUNT()
FROM Case
WHERE AccountId = :accountId
AND IsClosed = false
];
}
}The class has one method, takes one typed parameter, and returns an Integer. It returns no Case records, no names, and no fields. That is the shape a without sharing class should have: a small surface that produces only the data the feature has a right to expose.
Now compare a controller that uses it:
public with sharing class AccountSummaryController {
public static List<Case> myVisibleCases(Id accountId) {
// Record-level sharing applies here
return [SELECT Id, Subject FROM Case WHERE AccountId = :accountId];
}
public static Integer totalOpenCases(Id accountId) {
// Delegates to a class that bypasses sharing, for the count only
return OpenCaseCounter.countOpenForAccount(accountId);
}
}The controller stays with sharing. Only the single operation that needs system-wide visibility is delegated. The user sees a list limited to their own access and a total that is intentionally wider.
How it behaves in a call chain
A method runs under the sharing mode of the class that defines it, not the class that called it. When a with sharing class calls a without sharing class, the callee runs without sharing. When the callee returns, the caller continues with sharing.
Because the mode attaches to the defining class, without sharing cannot leak sideways into the caller's other methods. The reverse is the risk. Any code anywhere in the org can call a public method of your without sharing class, and that method will bypass sharing for whoever invoked it. Treat every public or global method in such a class as an exposed capability.
Keeping the blast radius small
Use these rules when you write a without sharing class.
- Keep the class small and single-purpose. Put only the operations that need the bypass in it. Do not turn it into a general "service" class.
- Return the least data that satisfies the feature. Prefer counts, booleans, and IDs to full records. If you return records, select only the needed fields.
- Validate inputs. Use typed parameters, bind variables, and explicit checks. The class sees all records, so a sloppy filter can return far more than intended.
- Do the permission check yourself where the business rule requires it. If a caller should only get a total when they have some entitlement, verify it in a
with sharinglayer before calling. - Document why. A comment stating the reason makes later review faster and stops someone from "fixing" it.
- Do not put it at the entry point. Controllers exposed to the UI,
@AuraEnabledmethods, REST resources, and@InvocableMethodclasses should not bewithout sharingunless the whole feature is intentionally unrestricted.
public without sharing class ExternalIdChecker {
// Returns only a boolean so no record data leaves this class.
public static Boolean isExternalIdTaken(String externalId) {
if (String.isBlank(externalId)) {
return false;
}
return [
SELECT COUNT()
FROM Account
WHERE External_Id__c = :externalId
] > 0;
}
}This sample assumes a custom text field External_Id__c exists on Account. Replace it with a field in your org.
Combining it with user-mode operations
without sharing removes the record filter, but it does not make a query respect field-level security or object permissions. It also does not add them. If a bypassing class must still honor what the user may read or write at the object and field level, you need to enforce that deliberately, for example with user-mode SOQL. A later chapter covers WITH USER_MODE and AccessLevel.USER_MODE.
What stays the same under without sharing
Some behavior does not change when you use the keyword:
- Object permissions and field-level security are not enforced by default in either mode. Declaring
with sharingdoes not enforce them either. - Triggers run in system context, and the sharing keyword rules for classes called from them follow the called class's own declaration.
- Governor limits still apply. Bypassing sharing may return more rows, so queries over large objects can hit row limits sooner.
Review checklist for a without sharing class
Before you accept a without sharing declaration in code review, check:
| Question | Acceptable answer |
|---|---|
| Is there a written reason? | A comment names the business need. |
| Is the class small? | Only the operations needing the bypass are present. |
| What leaves the class? | Counts, flags, IDs, or tightly scoped fields. |
| Who can call it? | Only intended callers, not UI entry points directly. |
| Is user input bound and validated? | Yes, using bind variables and typed parameters. |
| Could `with sharing` or `inherited sharing` work instead? | No, because the feature needs wider visibility. |
Exercise
A with sharing controller method calls OpenCaseCounter.countOpenForAccount(id), where OpenCaseCounter is declared without sharing. The controller then runs its own [SELECT Id FROM Case] on the next line. Under which sharing mode does each query run, and why?
Show answer
The query inside countOpenForAccount runs without sharing, because a method uses the sharing mode of the class that defines it. The controller's own query on the next line runs with sharing, because control returned to a with sharing class. The bypass is limited to the callee.
Exercise
A teammate makes a whole AccountService class without sharing so that one method can check for duplicate external IDs. What would you change, and why?
Show answer
Move the duplicate check into a small without sharing class that returns only a Boolean, and keep AccountService with sharing. This limits the bypass to the one operation that needs it. Otherwise every method in AccountService would ignore the user's record access.