6

Salesforce Dynamic SOQL

Salesforce is a powerful platform that provides developers with a range of tools for interacting with its vast database. One such tool is SOQL (Salesforce Object Query Language), which allows you to query the Salesforce database. However, in some cases, you might need to create flexible queries that can adapt to different user inputs or conditions. This is where Dynamic SOQL comes into play.

What Is Dynamic SOQL In Apex?

Dynamic SOQL Salesforce refers to the ability to construct SOQL queries as strings at runtime in Apex code. Unlike static SOQL, where the query is hard-coded, Dynamic SOQL provides the flexibility to build queries dynamically based on various conditions, user inputs, or logic that might not be known until the code is executed.

Example of Dynamic SOQL in Salesforce

Let’s consider a real-world scenario where a dynamic SOQL query salesforce is useful.

Suppose you have a Visualforce page where users can search for accounts based on their input, such as account name, industry, or rating. Instead of writing multiple static SOQL queries for each possible combination, you can use dynamic SOQL to construct the query based on the user’s input.

public with sharing class AccountSearchController {     public String searchTerm { get; set; }     public String industryFilter { get; set; }     public String ratingFilter { get; set; }     public List getAccounts() {         String queryString = 'SELECT Id, Name, Industry, Rating FROM Account WHERE Name LIKE \'%' + searchTerm + '%\'';         if (industryFilter != null && industryFilter != '') {             queryString += ' AND Industry = \'' + industryFilter + '\'';         }         if (ratingFilter != null && ratingFilter != '') {             queryString += ' AND Rating = \'' + ratingFilter + '\'';         }         return Database.query(queryString);     } }

In this example, the SOQL query string is dynamically built from the user’s input, enabling a flexible, powerful search experience.

How to Write a Dynamic SOQL Query in Salesforce

To write a dynamic SOQL query in Salesforce, you’ll typically use the Database.query() method in Apex. This method allows you to pass a string containing your SOQL query and returns a list of sObjects that match the query.

Here’s a basic syntax of how to write dynamic SOQL syntax Salesforce:

String queryString = 'SELECT Id, Name FROM Account WHERE Name LIKE \'A%\''; List<Account> accounts = Database.query(queryString);

In this example, the query string is created at runtime and passed to the Database.query() method to retrieve a list of Account records whose names start with the letter ‘A’.

Query Method of the Database Class

The Database.query() method is the primary way to execute dynamic SOQL in Apex. This method requires a single argument: the SOQL query string. Once executed, it returns a list of sObjects that match the query criteria.

Here’s how you can use it:

String queryString = 'SELECT Id, Name FROM Contact WHERE Email = \'[email protected]\''; List<Contact> contacts = Database.query(queryString);

In this example, the query string is dynamically created to search for a contact with a specific email address.

Using Dynamic SOQL Bind Variables

Bind variables in dynamic SOQL help protect against SOQL injection attacks and improve code readability. Instead of concatenating user input directly into the query string, you can use bind variables to safely insert values.

public with sharing class ContactSearchController { public String emailFilter { get; set; } public List<Contact> getContacts() { String queryString = 'SELECT Id, Name, Email FROM Contact WHERE Email = :emailFilter'; return Database.query(queryString); } }
Salesforce Business Analyst Career Training
Next Topic

Need more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

Frequently Asked Questions

Why do we use Dynamic SOQL?

Dynamic SOQL in Apex is used to structure a query that cannot be identified at compile time. It allows developers to create flexible, adaptable queries rather than writing multiple static queries.

What is SOQL Injection?

Apex SOQL injection is a security risk that occurs when user-supplied input is directly added to a SOQL query without proper validation.

Is Dynamic SOQL better than Static SOQL?

Static vs Dynamic SOQL depends on the use case. Static SOQL is used whenever a query structure is known at compile time, is validated by the Apex compiler, and is safer. Whereas, Dynamic SOQL is used whenever a query structure is determined at runtime based on user inputs. It requires extra focus on the security and governor limits.

Book Free15-Minutes Career Counselling