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?
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:
- In a Visualforce page where I want to dynamically change the query, order by, columns queried, etc. based on user actions.
- 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.
If you are developing outside of a managed package (i.e. for a particular organization), then its best to use static SOQL as:
- You get the compile time validation mentioned in the other answers
- 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.