Using Variables In Dynamic SOQL

Well how many times you have tried to use a list variable in a Dynamic SOQL?
We generally use Database.query() ,  which takes a query in string format and returns a List of sObject . The problem comes when want to use "IN" statement or want to use "date/date time" in a Dynamic query . I really tried a lot of combination, formatting the data,escapes etc.But finally was surprised to see if you just include the variable inside the query String, it just works !!!

Wasn't clear enough??

See the below example  which shows how to query all the accounts that are created today:

//initialize the Datetime with current time
DateTime now =; 
//query accounts by merging the variable name inside the query string 
List<Account> accountList = Database.query('SELECT Id FROM Account WHERE CreatedDate =:now'); 

Please Note :  that the variable "now" is included in the string itself.


  1. Is there a way to select the system date time in a SOQL query? For example: SELECT Id, FROM Account

    1. Well you can't pick System datetime in a query. You can simply do "Datetime dt =" and use the variable "dt" wherever needed.

    2. Thanks. I was just hoping there would be something, like in MS SQL : SELECT GETDATE(), ....... that I could include in my query.

    3. Karen I am not much aware about MS SQL, but APEX has lot of similarities with JAVA. If you are aware about Java you can easily code