A clear explanation of how WITH SECURITY_ENFORCED and Apex system mode differ — and best practices for secure SOQL.
What this post covers
This article explains the practical differences between executing SOQL with security enforcement and running Apex in system mode (without security). You’ll learn when to use WITH SECURITY_ENFORCED, what “without sharing”/system mode means, and simple best practices to avoid exposing sensitive data.
Quick summary
Using WITH SECURITY_ENFORCED in SOQL ensures Salesforce enforces object- and field-level security (OLS and FLS) for the running user. Apex that runs in system mode (default) or classes declared without sharing can bypass user permissions and sharing rules — which is useful for backend operations but risky for user-facing code.
Example: With Security
List<Account> accounts = [SELECT Name, Email__c FROM Account WITH SECURITY_ENFORCED];
// This will fail or return only accessible fields/rows if the user lacks permissions.
Example: Without Security
List<Account> accounts = [SELECT Name, Email__c FROM Account];
// Apex executes in system mode and may return fields or records the user cannot access.
Key differences
- Field-Level Security (FLS) — WITH SECURITY_ENFORCED enforces FLS; system mode does not.
- Object-Level Security (OLS) — WITH SECURITY_ENFORCED respects OLS; system mode can access objects the user can’t.
- Sharing rules — Queries in user context or classes declared with sharing respect sharing; without sharing ignores sharing.
- Error handling — WITH SECURITY_ENFORCED throws an exception if the user lacks access for queried fields/objects.
Best practices for secure SOQL
- Use WITH SECURITY_ENFORCED for user-facing code and integrations where data must respect user permissions.
- Limit use of without sharing and system mode to trusted backend processes that require elevated access.
- Always use bind variables in SOQL to prevent SOQL injection.
- Check field accessibility programmatically when necessary using Schema.DescribeFieldResult methods.
- Apply LIMIT and sensible filters to reduce large queries and improve performance.
When to choose which
Choose WITH SECURITY_ENFORCED when returning data directly to users or external systems that should observe Salesforce security. Use system mode/without sharing when performing admin-level operations (data migrations, cleanup jobs) — but keep elevated operations isolated, audited, and run under service accounts where possible.
Conclusion
Respecting Salesforce security models with WITH SECURITY_ENFORCED and explicit sharing declarations keeps sensitive data protected and reduces compliance risk. Only bypass security intentionally and with controls (logging, limited execution windows, and admin-only contexts).
For Salesforce admins, developers, and business users: adopting security-first query practices prevents accidental data leaks, simplifies audits, and builds trust across your organization.
For more, please follow our page!








Leave a Reply