Database Operations Run in User Mode by Default, Not System Mode

Take advantage of an enhanced Apex security model that protects your data though default object- and field-level access enforcement. Apex database operations, such as SOSL and SOQL queries, DML statements, and Database methods, now run in user mode by default. In user mode, database operations enforce the sharing rules, field-level security, and object permissions of the current user. In earlier API versions, database operations default to system mode, which means that the current user can access all data regardless of their permissions.

Where: This versioned change applies to API version 67.0 and later. The change applies to Lightning Experience and Salesforce Classic in Enterprise, Performance, Unlimited, and Developer editions.

Why: The new “secure by default” security paradigm prevents data visibility risks that can occur when you omit an access mode on database operations. Database operations bypass object- and field-level security settings only if you explicitly set them to run in system mode. This requirement promotes intentionality and ensures that you use system mode only when necessary.

How: To determine the access mode of a database operation regardless of the API version, we recommend that you always set an access mode explicitly.

To set the access mode for a SOSL or SOQL query, use the WITH USER_MODE or WITH SYSTEM_MODE clauses.

Account acc = [SELECT Id FROM Account WHERE Name = 'Singha' WITH USER_MODE LIMIT 1];
Note
Note The WITH SECURITY_ENFORCED clause is removed as of API version 67.0. Use WITH USER_MODE instead.

To set the access mode for a DML operation, use the as user or as system keywords.

Account a = [SELECT Id, Name 
   FROM Account
   WHERE Support__c = 'Premier' 
   WITH USER_MODE];
a.Rating = 'Hot';
update as user a;

To set the access mode for a Database or Search method, set the accessLevel parameter to AccessLevel.USER_MODE or AccessLevel.SYSTEM_MODE.

Account a = Database.query('SELECT Id, Name 
    FROM Account 
   WHERE Rating = \'Hot\'',  AccessLevel.USER_MODE);
Note
Note If you set a database operation to user mode, the operation respects the user’s sharing rules and overrides the calling class’s sharing declaration. However, if you set the operation to system mode, the sharing declaration of the calling class determines whether the operation respects the user’s record-level permissions.