2

I don't currently have an org with sufficient data to test this, and I've not been able to find a definitive answer so far.

Would a with sharing declaration on an Apex class affect the selectivity of a SOQL query contained within it?

For example, let's say that you have a custom index on a text field - let's call it Test_Value__c - on Opportunity, and you have 5 million records in there, where 4.5 million have the same value - Example - for this field.

If the Opportunity trigger contains the query:

SELECT Id FROM Opportunity WHERE Test_Value__c = 'Example'

then this looks like it is going to be non-selective. However would the platform still regard it as such if there were a private sharing model, the class had a with sharing declaration and as a result the executing user could only see 100 of the 5 million original records?

3
  • the recs have to be found first in order to apply sharing rules
    – cropredy
    Jul 9, 2020 at 1:17
  • @cropredy I suggest that is then an answer - selectivity is not affected because sharing rules must be applied "after the fact" to filter out inaccessible records?
    – Phil W
    Jul 9, 2020 at 8:26
  • Why would it not impact selectivity if it was a private sharing model? Jul 9, 2020 at 11:39

1 Answer 1

5

Sharing does not affect query selectivity

The records have to be located first before the sharing rules can be applied. If you think about it, record visibility includes:

  • The Org Wide Defaults
  • Criteria-Based Sharing Rules
  • Manual sharing
  • Apex sharing
  • Record ownership
  • Role hierarchy
  • Territories
  • Account/etc team membership

Salesforce, in effect, uses a Separation of Concerns pattern wherein the SOQL engine fetches records, presents these to the sharing/visibility layer which applies all of the above, and the result of the sharing/visibility is then made available to the running user's transaction.

More on Sharing and Record Visibility

2
  • This is what I thought happened - it made sense otherwise you could have certain users getting non selective query errors whilst others didn't. However, I discovered this article - help.salesforce.com/… - which made me think again, specifically the answer: "Profiles which have view all rights don't go through sharing evaluation and SQLs run will be different compared to profiles with limited view of data. Depending on selectivity we drive from Sharing or selective filters, whichever is most efficient."
    – dyson
    Jul 22, 2020 at 22:20
  • good point and an obvious optimization for SFDC
    – cropredy
    Jul 22, 2020 at 22:38

You must log in to answer this question.

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