Using the with sharing or without sharing Keywords

Use the with sharing or without sharing keywords on a class to specify whether or not to enforce sharing rules.

The with sharing keyword allows you to specify that the sharing rules for the current user be taken into account for a class. You have to explicitly set this keyword for the class because Apex code runs in system context. In system context, Apex code has access to all objects and fields— object permissions, field-level security, sharing rules aren’t applied for the current user. This is to ensure that code won’t fail to run because of hidden fields or objects for a user. The only exceptions to this rule are Apex code that is executed with the executeAnonymous call and Chatter in Apex. executeAnonymous always executes using the full permissions of the current user. For more information on executeAnonymous, see Anonymous Blocks.

Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user. For example:

public with sharing class sharingClass {

// Code here

}

Use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are not enforced. For example:

public without sharing class noSharing {

// Code here

}
Some things to note about sharing keywords:
© Copyright 2000–2014 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.