Salesforce Sharing Rules and the with sharing Keyword
Sharing rules decide who can open a record. The with sharing keyword decides whether your Apex enforces that decision, what it skips, and what a query still lets through.
TL;DR
A sharing rule decides which records a user can open. The with sharing keyword on an Apex class decides whether your code enforces that decision. The keyword only covers record-level access. It does not grant object permissions, and it does not protect field-level security. Since API version 67.0, Apex also runs in user mode by default, so field access is enforced unless you ask for WITH SYSTEM_MODE. Put the keyword on every class you write, and say out loud which access mode each query runs in.
What a Sharing Rule Actually Decides
Salesforce decides record access in layers. The org-wide default sets the floor. With the default set to Private, nobody sees a record they do not own, share, or reach through their role. Every layer above that floor can only add access, never take it away.
The layers, roughly in the order a request meets them:
- The org-wide default for the object.
- Sharing rules: criteria-based grants, such as "every account owned by a user in the West region is readable by the West team."
- Manual sharing, and Apex sharing entries that code writes at runtime.
- Teams, territories, and the role hierarchy.
A sharing rule has two halves. A criterion picks the records, and an access level says what the target can do with them: read, or read and write. The target is a user, a group, a queue, or a territory. A rule lives on one object, so a rule on Account does nothing for Opportunity.
Two things a sharing rule never does. It cannot hand over an object a user has no permission for at all, because object permissions are a separate layer. And it cannot expose a field the user cannot see, because that is field-level security. A rule gives away records, not fields.
When a Sharing Rule Bites
Sharing rules only ever add access. They are automatic exceptions to the org-wide default, and they can never be stricter than that default. That is why they matter on objects whose default is restrictive. When the default is Private or Public Read Only, a rule opens records back up for a named group of users. When the default is Public Read/Write, everyone already sees every record and a rule has nothing left to extend.
Sharing rules also only add access on top of what the user already has. A user who owns a record keeps it no matter what the rules say. And the rules are evaluated for the running user, so code that runs in system mode ignores them completely.
The Three Keywords
Every class you write should carry one of three keywords.
with sharing enforces the current user's record-level access. It is the mode you want for anything a person triggers: a controller, an @AuraEnabled method, an Apex REST service, a batch job that works through a user's records.
without sharing ignores record-level sharing. It lets your code read and write records the running user cannot see. Use it only when the elevated access is the point, and only for the records that need it.
inherited sharing takes the mode from whoever called the class. It is the flexible choice for service classes that get called from more than one place.
Two rules surprise people. The mode comes from the class where a method is defined, not from the class that calls it, so a with sharing method keeps enforcing sharing even when a without sharing class calls it. And an inherited sharing class runs as with sharing whenever it is the entry point of a transaction, so in the place you most often test it, it behaves like with sharing.
public with sharing class AccountService {
public static List<Account> recentAccounts() {
return [
SELECT Id, Name, Industry
FROM Account
ORDER BY CreatedDate DESC
LIMIT 10
];
}
}public without sharing class AccountAdminService {
public static List<Account> allAccounts() {
return [SELECT Id, Name FROM Account];
}
}public inherited sharing class AccountLookup {
public static List<Account> accounts() {
return [SELECT Id, Name FROM Account];
}
}What with sharing Does Not Protect
Here is the trap that catches experienced developers. The sharing keyword governs record-level access only. It does not check whether the user may read the object, and it does not check whether the user may read the field.
I checked that against a scratch org, using a user who has no access to Account at all. Under with sharing the query failed with "Access to entity 'Account' denied." Under without sharing it failed with the same message. Only WITH SYSTEM_MODE returned the record. So without sharing is not admin mode. It lifts record access and nothing else.
The second trap hides in plain sight. An administrator with Modify All Data sees the same rows under every mode, because that admin already sees everything. A sharing bug can sit in production for months, because the only person testing it is the one person who cannot reproduce it.
Access Mode: the Other Switch
Object permissions and field-level security are controlled separately, by what Salesforce calls the access mode. WITH USER_MODE on a query enforces the user's object permissions and FLS. WITH SYSTEM_MODE skips both. The same choice exists for Database methods, as AccessLevel.USER_MODE and AccessLevel.SYSTEM_MODE.
List<Account> accounts = [SELECT Id, Name FROM Account WITH USER_MODE];public class AccountMaintenanceJob {
public static List<Account> accountsForCleanup() {
return [SELECT Id, Name FROM Account WITH SYSTEM_MODE];
}
}String query = 'SELECT Id, Name FROM Account LIMIT 10';
List<Account> accounts = Database.query(query, AccessLevel.USER_MODE);Two changes in API version 67.0, which shipped in Summer '26, matter here. Database operations now default to user mode, so a query that used to skip FLS now respects it. And a class with no sharing keyword now runs as with sharing instead of taking the mode of its caller. WITH SECURITY_ENFORCED no longer compiles at all. The compiler tells you to use WITH USER_MODE instead.
That means code you wrote years ago behaves differently after an API version bump. If a class leaned on the old system-mode default, add WITH SYSTEM_MODE to the queries that genuinely need it, so the intent is visible rather than accidental.
One more practical note about system mode: you cannot use it from the console. Run a WITH SYSTEM_MODE query in anonymous Apex and the compiler rejects it with "Cannot use SYSTEM_MODE access level in anonymous execution of Apex." Put the query in a class when you want to check it, the way the example above does.
Field-Level Security: stripInaccessible
Some fields have to stay hidden even from users who can read the record. That happens when the data arrived from somewhere else: a client payload, a deserialized JSON blob, an inbound integration message. Security.stripInaccessible is the tool for it. You pass it the access you care about along with the records, and it hands back a copy with the fields the user cannot use taken out.
List<Account> accounts = [SELECT Id, Name, Phone FROM Account];
SObjectAccessDecision decision = Security.stripInaccessible(AccessType.READABLE, accounts);
Set<String> removedFields = decision.getRemovedFields().get('Account');
List<Account> safeAccounts = (List<Account>) decision.getRecords();One thing to know about it: the check on the parent object is on by default. For a user who cannot read Account at all, the call throws "No access to entity" instead of returning an empty copy, so guard it when you accept data from outside your org.
System.runAs
To see what another user sees, run the code as that user. System.runAs switches the running user for the block, and it only works inside a test method. Outside one it fails at runtime with "System.runAs can only be used within a test method." Wrap the query you care about in a test, switch users, and assert on the count.
@isTest
static void accountVisibilityFollowsTheRunningUser() {
// Replace with a user id from your own org.
User otherUser = [SELECT Id FROM User WHERE Username = 'some.user@example.com' LIMIT 1];
System.runAs(otherUser) {
Integer visibleAccounts = [SELECT COUNT() FROM Account];
System.assertEquals(0, visibleAccounts);
}
}Traps Worth Knowing
A few rules that cost people an afternoon:
- Queries against Pricebook2 ignore the
with sharingkeyword. All price books come back regardless of sharing. - Triggers always run in system mode. You cannot put a sharing keyword on a trigger, so put it on the handler class instead.
- Async Apex is a new entry point, which means an
inherited sharingclass runs aswith sharinginside a batch or queueable job. - Anonymous Apex and Connect in Apex always run with sharing.
Where To Practice Next
Put the ideas to work on the platform. The REST API wrapper class challenge is a good place to watch a with sharing service behave when an integration calls it. If you want the language first, Apex Fundamentals walks through Apex step by step.
For the security side, the create records from a client payload without trusting its fields challenge puts stripInaccessible to work on genuinely untrusted data, and the safe, allow-listed SOQL field list challenge covers building queries that respect field access.
For background, Salesforce Developer Interview Questions covers what interviewers ask about sharing and bulkification, and Apex DML Best Practices covers the operations that run inside this same security model.
About Warren Walters
Salesforce MVP and transformative mentor with 8+ years in the Salesforce realm. Founder of Lightning Challenge, dedicated to nurturing the next generation of Salesforce talent through hands-on practice and real-world coding challenges.
Visit Profile →