[SalesForce] SOQL inline query vs dynamic query

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?

Best Answer

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.