Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

When doing SOQL Queries, how I can I ensure that I only return the set of Objects that the current user has access to?

Imagine I query for Accounts, and I display a list of links to those Accounts on a VisualForce page. I only want to list those Accounts that the user has access to, otherwise the user clicks on a link but will get an Access Denied, which is not what we want.

How do I do that?

share|improve this question
You mean current user? – Artur Kępczyński Feb 14 '14 at 11:26
Sure, updated. Thanks. – Willem Mulder Feb 14 '14 at 11:28
@adtennant - answer fit your requiments – Artur Kępczyński Feb 14 '14 at 11:31
up vote 7 down vote accepted

Define the class that your SOQL query is within as with sharing.

This is covered by the online documentation here.

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.

And here is an example:

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
share|improve this answer
Excellent. Exactly what I need. – Willem Mulder Feb 14 '14 at 11:31

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.