4

I just wanted to know weather to use inline query or dynamic query as my daily practice. I know in some cases we have to use dynamic query. But as routine practice which one to use. Any thoughts?

6

SOQL Inline query has advantages if you can work within its less dynamic structure. Mainly, when your Apex is compiled it checks references to fields and objects in the inline SOQL. Compiler errors are good! It makes it less likely that you will run into strange runtime behavior

Database.query() is powerful, but since it queries on a string constructed by you, it is much more error prone.

In my experience, there have been two typical use cases where I have used Dynamic SOQL:

  1. In a Visualforce page where I want to dynamically change the query, order by, columns queried, etc. based on user actions.
  2. When creating dynamic Apex functionality where I want to query for any sObject type, but I won't know until I am passed that sObject type. The Apex describe features can help a lot with this.
8

If you are developing outside of a managed package (i.e. for a particular organization), then its best to use static SOQL as:

  1. You get the compile time validation mentioned in the other answers
  2. Apex variables bound in to static SOQL are not susceptible to SOQL injection attacks, whereas dynamic SOQL built up from user input needs to be protected.

However, if you are developing a managed package, dynamic SOQL is better as your application may be referencing fields or features that don't exist on the organisation you are deploying into.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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