function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
rushi ettam 7rushi ettam 7 

Consideration of sharing rules in apex

In Apex code Developers Guide
If we are using with and without sharing rules in our Apex class
We see the following:
Enforcing the current user's sharing rules can impact:
• SOQL and SOSL queries. A query may return fewer rows than it would operate in a system context.
• DML operations. An operation may fail because the current user doesn't have the correct permissions. For example, if the user
specifies a foreign key value that exists in the organization, but which the current user does not have access to.

Actually what is the sharing rule:  it provides the wider access to data
So, my Question here is:  how can  SOQL and SOSL queries return fewer rows
it has to return more rows because sharing rules provide additional access
and even with the ​ DML operations also we shouldn't get the error while performing any DML.

Thanks in advance.......


 
Best Answer chosen by rushi ettam 7
William TranWilliam Tran
Again, in the UI sharing rules allow wider access since security is enhanced.

For example user 1 can see 2 contacts, and with sharing rule he can now see 5.

In Apex, the code sees ALL contacts say 10 (since it has no security restrictions).  
Apex with sharing rule, the code can now only see 5.

So in UI, sharing rules allow wider access but in 
Apex with sharing rules access is narrowed.

Thx

All Answers

William TranWilliam Tran
Good point except Apex without sharing rules mean it bypass all the security/sharing rules.

So yes, sharing rules provide the wider access to data when in the UI.

But Apex code is not restricted to security/sharing rules unless you explicitly add with sharing.

As a common practice, if your question is answered, please choose 1 best answer. 
But you can give every answer a thumb up if that answer is helpful to you. 

Thanks
rushi ettam 7rushi ettam 7
Thank you for the reply

But here my point is in  Apex without sharing rules also we can access all org data. So, why we need to use sharing rules for wider access to data
And one more thing  you said:
sharing rules provide the wider access to data when in the UI.
what does that mean
it's bit confusing to me
 
William TranWilliam Tran
Again, in the UI sharing rules allow wider access since security is enhanced.

For example user 1 can see 2 contacts, and with sharing rule he can now see 5.

In Apex, the code sees ALL contacts say 10 (since it has no security restrictions).  
Apex with sharing rule, the code can now only see 5.

So in UI, sharing rules allow wider access but in 
Apex with sharing rules access is narrowed.

Thx
This was selected as the best answer