If a portal user only has permission to access a subset of records, defined via sharing rules, should the SOQL still use a WHERE clause, or should it be left off of the query?

List<MyObject__c> myObjects = [SELECT Id, Name FROM MyObject__c];


List<MyObect__c> myObjects = [SELECT Id, Name FROM MyObject__c WHERE Parent_Contact__c = :contactId];


The bottom line question is: Should the WHERE clause always be added to the query, or would it be considered overkill when sharing is enforced?

  • What Mohith said is correct. In addition, if you are executing your code in a trigger, then the it is executed in System mode i.e. the current user's permissions, field-level security, and sharing rules aren’t taken into account during code execution. Jan 29, 2013 at 14:53
  • Thanks @ShaileshDeshpande. I am interested to know whether it would be considered a good idea to include the WHERE clause even when sharing rules are enforced, or if it is considered overkill when sharing has been specified. Jan 29, 2013 at 17:33
  • Ohh..in that case I would prefer a plain query as along as I dont have to access a subset of the records that are returned. I'll add a where clause only to get the specific records. Jan 29, 2013 at 18:07

2 Answers 2


While sharing covers most of your access needs as Mohith has mentioned there's another aspect: performance.

If you're planning on dealing with more than a few thousand custom objects in the table then your first query will put signifigantly more stress on salesforce in terms of what sharing calculations to perform, whereas the second will have a much, much smaller result set for salesforce to evaluate sharing against.

Salesforce's sharing model is actually patented, which lets us get a peek under the covers of how it works.

|0046| shows there's a join or join-like operation going on which would need to pull in all share rules and group membership and filter the results from MyObject__c in your first query. If this is in fact the case then the filtering of your table against the sharing table will have more overhead than taking a known shared result set and joining it to the share table.


It will depend whether you have kept your class as "with sharing" and "without Sharing"

When you use with sharing all the sharing rules will apply and query will return result according to the sharing rules set for the logged in user .


Following above link will help you .

  • 1
    I wish I could upvote twice :) Usually I aim at keeping the code simple so no WHERE clause. But then I make a long comment on the top of the class to specify where it relies either on explicit "with sharing" or why I've left [blank] on purpose (blank = the caller's context decides). Somebody else will maintain it, any hints on "what can break if I do this" are always greatly appreciated.
    – eyescream
    Jan 29, 2013 at 21:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .