Dynamic variables in SOQL Query Apex

by Rijwan Mohmmed
0 comment

Hello friends, today we are going to discuss Dynamic variables in SOQL Query Apex. In Apex, dynamic variables can be used in SOQL (Salesforce Object Query Language) queries to make them more flexible and adaptable to changing data. By using dynamic variables, you can modify the query at runtime, allowing you to retrieve data based on user input or other changing conditions.

Also, check this: Use Map Collection In Apex

Key Highlights :

  1. To use dynamic variables in a SOQL query, you can use the String.format() method to create a dynamic SOQL.
  2. Execute the query using the Database.query() method.
  3. We can also use SOQL Bind variables for filter conditions, order by, limit, and offset clauses.
  4. Best practice to use bind variables in SOQL queries, as it helps to prevent SOQL injection attacks and improves performance by caching query plans
  5. Dynamic variables in SOQL queries are a powerful tool that can help you create more flexible and adaptable queries.

Code :

For example, consider the following code that queries the Account object for all accounts with a specific Name:

String accountName = 'Acme Inc.';
String query = 'SELECT Id, Name FROM Account WHERE Name = \'' + accountName + '\'';
List<Account> accounts = Database.query(query);

In the above code, the accountName the variable is used in the SOQL query to filter the results based on the name of the account. This allows the query to be flexible and adaptable to different values of accountName.

Another way of using dynamic variables in SOQL is by using bind variables also known as placeholder. Placeholder is a place holder in a query that you replace with a variable value before you execute the query. For example,

String accountName = 'Acme Inc.';
String query = 'SELECT Id, Name FROM Account WHERE Name = :accountName';
List<Account> accounts = Database.query(query);

In this example, :accountName is a placeholder, and the actual value of accountName is passed to the query at runtime.

Output :

Reference :

  1. Dynamic SOQL

You may also like

Leave a Comment