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
Steve RossSteve Ross 

Difference between database.query and SOQL statement?

Seems to me that the following achomplish the same thing:

List<Account> aa = [SELECT Id, Name FROM Account WHERE Name = 'Acme'];

List<Account> aa = databse.query('SELECT Id, Name FROM Account WHERE Name = 'Acme'');

What are the advantages of using one over the other?
Stephan SpiegelStephan Spiegel
Using database.query allows you to dynamically create the query string during runtime. Maybe you don't know until runtime which fields you want to include in your query, or your WHERE clause should be constructed differently based on something that happened earlier in the code. You could even query on different objects, depending on what's needed.

Having said that, you should prefer the SOQL query whenever possible. When you use a dynamic query, Salesforce doesn't know what the query is until your code actually runs, and it can't prevent you (or someone not familiar with your code) from accidentally deleting fields needed in a query. If you use a hard-coded query, Salesforce will track those fields, making your code more robust.
Steve RossSteve Ross
Thanks!
Leanbridge TechnologiesLeanbridge Technologies
Database. the query can be used wherever a static SOQL query can be used, such as in regular assignment statements and for loops. Unlike inline SOQL, fields in bind variables are not supported. So the fundamental difference is the lack of support for variable binding.
Leanbridge TechnologiesLeanbridge Technologies
Best Practices for Apex Classes and Apex Triggers ... Take an example such as when you are creating a web or email service. ... Avoid trigger recursion via a static variable when performing an update on the same object from the trigger. ... Most of the code can be included in this helper/handler class
kailash chandrakailash chandra
Hi Steve,
Basically, we need database.query, whenever we need to make a dynamic SOQL statement .
egample:

1. I'm creating a managed package and don't want to take an explicit dependency on a feature. E.g. List<sobject> revenueSchedules = Database.query('Select Id from OpportunityLineItemSchedule where OpportunityLineItemId in :oliIds'); If I did this in static SOQL all the installers of the managed package would need Product Schedules enabled.

2. I want to dynamically include an optional field or filter in the SOQL query. A custom setting may define the name of a field that should be used to populate something else. As it isn't known at "compile" time it needs to be dynamic.