Variable Binding in Dynamic SOQL

Are you used to writing Apex like the following for building a dynamic SOQL query in Salesforce? If so, read on for a better way.

Variable Binding: A Better Way

Using Variable Binding, there’s no more need to build the “IdInClause” anymore. The equivalent Apex code using Variable Binding is:

This code is cleaner and takes less time to execute. Variable Binding also prevents SOQL injection natively without the use of the escapeSingleQuotes() string function to cleanse string input.

Variable Binding does have limitations, however. It can’t bind directly against functions in the query string like

It also can’t bind against fields on sObjects like

Both cases can still be done by assigning the value(s) to a variable first and then binding against that in the query.

Happy Coding,


Invalid Cross Reference Id Error

Getting the “Invalid Cross Reference Id” Salesforce error and unsure what it means? If so, that error means that the Salesforce Id used in a lookup or master-detail relationship field is not valid.


1) Wrong Object Type – The relationship field is being set to the Salesforce Id of the wrong object. For example, if field A is a lookup to the Account object, an opportunity Id can’t be used in this field.

2) Record Deleted – The record no longer exists. This can happen if someone deleted the record while a user or the system is inserting or updating records. It can also happen during a request when the record is initially inserted but then rolled back so the code still has a reference to the record with an id in memory but the record does not exist in the database.

3) Relationship Field Pointing To Wrong Object – This happens less frequently but is still a cause of this error. Sometimes, there are multiple objects in the system with the same name and a user chose the wrong object to have the lookup or master-detail point to. This happens because Salesforce will show the same object name without any further detail in the object list when defining the field so it’s not immediately clear which to choose.

To choose the correct object when there are multiple with the same name, inspect the drop down list in the browser and view the values for the select list items. Identify the correct one to use and then choose it from the drop down list.

If this information has helped or if you have other causes, please comment below.

Happy Coding,



Welcome To Metillium!

This site was started to share Microsoft & Salesforce information with everyone.


– Share Microsoft & Salesforce Knowledge

– Contribute to Microsoft & Salesforce communities

– Contribute to Open Source Software

About Me

Started developing professionally in 2007 using Microsoft technology to create applications. Since 2011, Salesforce has been my primary technology platform to create applications.