Sub topic 4
Querying with WITH USER_MODE
What this chapter assumes
You should already know basic Apex syntax and classes, how to write SOQL queries, and how profiles and permission sets grant object permissions (CRUD) and field-level security (FLS). Earlier chapters showed that Apex runs in system mode by default, and that with sharing controls record visibility but not CRUD or FLS. This chapter shows how to make a static SOQL query respect all three.
The problem the clause solves
A plain query in Apex reads whatever the code asks for. Consider this method:
public with sharing class AccountLookup {
public static List<Account> recent() {
return [SELECT Id, Name, AnnualRevenue FROM Account ORDER BY CreatedDate DESC LIMIT 10];
}
}with sharing limits the rows to records the user can see. It does not check whether the user can read the Account object, and it does not check whether the user can read AnnualRevenue. If a Lightning component calls this method, a user whose profile hides that field still receives its value.
WITH USER_MODE closes that gap inside the query itself. You add one clause, and the platform checks the running user's permissions as the query executes.
Syntax and placement
The clause goes after WHERE and before GROUP BY, ORDER BY, and LIMIT:
public with sharing class AccountService {
public static List<Account> getAccounts() {
return [
SELECT Id, Name, Industry
FROM Account
WHERE Industry != null
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}If the query has no WHERE clause, WITH USER_MODE follows the FROM clause directly.
List<Contact> contacts = [SELECT Id, LastName, Email FROM Contact WITH USER_MODE];The clause works anywhere a static query works. You can use it in an assignment, in a for loop over a query, and with bind variables:
public with sharing class ContactReader {
public static Integer countEmails(Id accountId) {
Integer total = 0;
for (Contact c : [
SELECT Id, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
]) {
if (c.Email != null) {
total++;
}
}
return total;
}
}User mode for queries is available in recent API versions. If your org or project is on an old API version for a class, check that the class compiles before assuming the clause is supported.
What the query enforces
User mode checks three things for the user who is running the code.
| Check | What it covers | What happens on failure |
|---|---|---|
| Object permission | The user needs Read on every object in the query, including objects reached through relationships and subqueries | The query throws a `QueryException` |
| Field-level security | The user needs read access to every field the query references | The query throws a `QueryException` |
| Sharing | Only records the user can see through ownership, role hierarchy, sharing rules, and manual shares | Rows are removed from the result with no error |
The third row differs from the first two. A missing permission is an error, while a missing record share is invisible. A user who cannot see 40 of 50 matching accounts receives 10 rows and no warning. Write code that does not treat "fewer rows than expected" as a failure.
Fields in WHERE and ORDER BY are checked too
A common assumption is that only the fields you select matter. In user mode, every field the query references is checked, including fields used only for filtering or sorting:
// Fails for a user who cannot read Account.Rating, even though Rating is not selected
List<Account> hot = [
SELECT Id, Name
FROM Account
WHERE Rating = 'Hot'
WITH USER_MODE
];This closes a real leak. Without the check, a user could learn the value of a hidden field by running filtered queries and watching which rows come back. The same applies to ORDER BY: the order of the rows would reveal information about a field the user cannot read.
Relationships and subqueries
Parent fields reached by dot notation need field access on the parent object, and the user needs Read on the parent object:
List<Contact> contacts = [
SELECT Id, LastName, Account.Name, Account.Industry
FROM Contact
WITH USER_MODE
];If the user can read Contact but not Account.Industry, this query fails. Child subqueries get the same treatment. In the next example the user needs Read on Opportunity, and read access on Amount and StageName, as well as Account access:
List<Account> accounts = [
SELECT Id, Name, (SELECT Id, Amount, StageName FROM Opportunities)
FROM Account
WITH USER_MODE
];How the decision is made
The platform evaluates permissions while it processes the query. It does not run your code first and filter afterward.
Sharing is enforced even in without sharing classes
User mode enforces the user's sharing rules no matter how the class is declared. This is a difference from the older approaches, where sharing depended on the class keyword.
public without sharing class LooseService {
public static List<Account> visibleToUser() {
// Sharing rules of the running user still apply to this one query.
return [SELECT Id, Name FROM Account WITH USER_MODE];
}
public static List<Account> everything() {
// No clause: system mode, and the class is without sharing, so all rows.
return [SELECT Id, Name FROM Account];
}
}The clause overrides the class setting for that statement only. Other statements in the same class keep their normal behavior.
Even so, declare with sharing on classes that handle user-facing data. It keeps the unannotated queries and the DML in that class consistent with what you intended, and a code reviewer can see the intent at a glance.
A worked before-and-after
Suppose a Lightning web component calls the following method. The users who open the component have Read on Account but no access to Account.AnnualRevenue.
public with sharing class RevenueController {
@AuraEnabled(cacheable=true)
public static List<Account> topAccounts() {
return [
SELECT Id, Name, AnnualRevenue
FROM Account
ORDER BY AnnualRevenue DESC
LIMIT 5
];
}
}In system mode, the method returns revenue figures to users who should not see them, and it sorts by the hidden field. Adding the clause changes that:
public with sharing class RevenueController {
@AuraEnabled(cacheable=true)
public static List<Account> topAccounts() {
try {
return [
SELECT Id, Name, AnnualRevenue
FROM Account
WITH USER_MODE
ORDER BY AnnualRevenue DESC
LIMIT 5
];
} catch (QueryException e) {
throw new AuraHandledException('You do not have access to revenue data.');
}
}
}For a user who lacks the field permission, the query now throws. The catch block turns the failure into a message the component can show. The chapter on handling permission failures covers that pattern in detail.
Edge cases and limits
- The permission check is per user, not per class. Permissions come from the user's profile and permission sets. A test that runs as an administrator will pass a query that fails for a standard user. Use
System.runAsto test realistic users, which a later chapter covers. - You cannot combine it with
WITH SECURITY_ENFORCED. The two clauses are alternatives. UseWITH USER_MODEin new code and replace the older clause when you touch a query. WITH SYSTEM_MODEexists. It states explicitly that a query runs in system mode. It documents intent, and it is useful when a default would otherwise be unclear. It does not add any protection.- Governor limits do not change. The clause does not add queries or consume extra SOQL rows. Standard limits apply as before.
- Failing fast is the design. The query does not drop an unreadable field and continue. If you want partial data, use
Security.stripInaccessible, which a later chapter compares with user mode. - Formula fields and fields they reference. Treat formula fields like any other field in the query. The user needs read access to the formula field itself. Do not assume the check applies to the formula's inputs, and test with a restricted user if it matters to you.
- Apex-defined access is not part of this. The clause governs the query. It does not stop your code from using data it already holds. If you query in system mode and pass the result along, user mode did nothing for those records.
Common errors
- Putting the clause in the wrong place. Writing
ORDER BY Name WITH USER_MODEproduces a compile error. The clause comes beforeGROUP BY,ORDER BY, andLIMIT. - Using it on only some queries. One unprotected query in a controller can undo the work done in the others. Review every query that returns data to a user.
- Catching the exception and ignoring it. An empty
catchblock turns a security failure into an empty list. The user sees nothing and the developer sees nothing. Log the failure and return a clear message. - Parsing the exception message. Message text for missing access can change and can differ between a missing object and a missing field. Catch the exception type and respond to the failure as a whole.
- Testing only as an administrator. System administrators usually have access to everything, so the test never exercises the failure path.
- Expecting an error when sharing hides rows. Sharing removes rows silently. A query that returns zero rows might mean "no matching records" or "no visible matching records."
Summary of the pattern
For a static query that serves a user, the safe default is short:
public with sharing class OpportunityService {
public static List<Opportunity> openForAccount(Id accountId) {
return [
SELECT Id, Name, StageName, Amount
FROM Opportunity
WHERE AccountId = :accountId AND IsClosed = false
WITH USER_MODE
ORDER BY CloseDate
LIMIT 200
];
}
}The class declares with sharing, the query carries WITH USER_MODE, and bind variables handle the input. The caller is responsible for handling the QueryException.
Exercise
A query selects Id, Name from Account and filters with WHERE Rating = 'Hot', using WITH USER_MODE. The running user can read Account and Account.Name but cannot read Account.Rating. What happens, and why?
Show answer
The query throws a QueryException. User mode checks field-level security on every field the query references, including fields that appear only in WHERE or ORDER BY. This prevents a user from inferring the hidden field's values from which rows are returned.
Exercise
A class is declared without sharing. It contains [SELECT Id FROM Account WITH USER_MODE]. Does the query return all accounts in the org?
Show answer
No. User mode applies the running user's sharing rules to that statement even though the class is without sharing. The query returns only the records the user can see. It also checks object permission and field-level security.
Exercise
Where must WITH USER_MODE appear in a query that has a WHERE clause, an ORDER BY clause, and a LIMIT clause?
Show answer
After the WHERE clause and before ORDER BY and LIMIT, for example SELECT Id FROM Account WHERE Industry != null WITH USER_MODE ORDER BY Name LIMIT 10.