- SalesforceChaCha
- Posts
- ๐ Dynamic SOQL ๐บ
๐ Dynamic SOQL ๐บ
The Wild West of Querying Salesforce Data
Good morning, Salesforce Nerds!
Letโs face it - static SOQL is dependable, but sometimes itโs just not enough. ๐ค
Itโs like ordering a plain cheese pizza when what you really need is one half with pineapple, the other with anchovies, and gluten-free crust for good measure. ๐
When your query needs to adapt to user input, variable filters, or shifting logic, dynamic SOQL steps in to save the day - capable, flexible, and just a little bit risky (in a good way, mostly).
Itโs time to query like itโs 2025. ๐

TABLE OF CONTENTS
Dynamic SOQL
LIKE MAD LIBS, BUT FOR QUERIES
WHAT IS DYNAMIC SOQL
Dynamic SOQL is what happens when Apex developers decide that static queries are just too vanilla. ๐ฅฑ
Unlike regular SOQL, which is hardcoded at compile-time, dynamic SOQL is constructed as a string at runtime.
This gives you the flexibility to build queries on the fly based on variables, user input, or complex logic. ๐ฅ
Hereโs what that looks like:
String objName = 'Contact';
String query = 'SELECT Id, Name FROM ' + objName + ' WHERE LastName = \'Smith\'';
List<SObject> results = Database.query(query);
๐๏ธ Need to add filters conditionally?
๐๏ธ Query different objects?
๐๏ธ Inject a bit of logic into your logic?
Dynamic SOQL lets you do all that. But, halt - there be dragons here. ๐
BECAUSE NOT EVERY FILTER IS A FOREVER FILTER
WHY GO DYNAMIC?
Dynamic SOQL shines in scenarios where the query structure is dependent on input:
๐๏ธ Search pages with optional filters
โป๏ธ Reusable utility classes across multiple SObjects
๐๏ธ Admin-controlled filters stored in Custom Metadata or Custom Settings
๐ค Complex logic paths in Apex that generate different queries per user or scenario
Imagine trying to cram five optional filters into a static query. No thanks.
Suddenly you're juggling if-else spaghetti just to add a WHERE clause. ๐คน
Dynamic SOQL elegantly sidesteps that mess - if you write it carefully.
But wait, isnโt this a security risk? ๐
Well, yes, it can be.
Dynamic SOQL opens the door to SOQL Injection, which is basically the evil twin of convenience. ๐
Think SQL Injection but Salesforce-flavored. Hereโs a tragic example:
String userInput = ApexPages.currentPage().getParameters().get('name');
String query = 'SELECT Id FROM Contact WHERE LastName = \'' + userInput + '\'';
List<Contact> contacts = Database.query(query);
Now imagine the user inputs: Smith' OR Name != '
This would resolve to:
SELECT Id FROM Contact WHERE LastName = 'Smith' OR Name != ''
Your WHERE clause just went rogue. Yikes. ๐ฑ
The fix? Rather easy, actually. Use binding:
String userInput = ApexPages.currentPage().getParameters().get('name');
String query = 'SELECT Id FROM Contact WHERE LastName = :userInput';
List<Contact> contacts = Database.query(query);
The :
operator in dynamic SOQL safely binds variables - no escape characters, no hijacking, just sweet, secure Apex. ๐
BECAUSE COPY-PASTING FROM STACKOVERLOW WONโT SCALE
BUILD-A-QUERY WORKSHOP
Hereโs a simple example to drive the point home. ๐๏ธ
Letโs say youโre building a dynamic search for Accounts with optional filters.
public List<Account> findAccounts(String type, String industry) {
String baseQuery = 'SELECT Id, Name FROM Account';
List<String> conditions = new List<String>();
if (type != null) {
conditions.add('Type = :type');
}
if (industry != null) {
conditions.add('Industry = :industry');
}
if (!conditions.isEmpty()) {
baseQuery += ' WHERE ' + String.join(conditions, ' AND ');
}
return Database.query(baseQuery);
}
Notice:
๐ We use String.join()
to build a conditional WHERE clause
๐ฆบ We use :binding
to inject values safely
๐ We still look cool doing it
YOU CAN BE A WIZARD OR A WANTED CRIMINAL
QUERY CRIMES AND HOW TO AVOID THEM
Before you start dynamically querying everything in sight like a SOQL sorcerer, letโs talk safety. ๐
Dynamic SOQL can be powerful - but without a little discipline, you might end up with a heap-sized disaster, a security breach, or just a deeply disappointed future-you.
Here are the commandments to follow and the cardinal sins to avoid: ๐๏ธ
โ
Always use bind variables (:
) for dynamic values
โ
Use Schema APIs (like Schema.getGlobalDescribe()
) to validate object/field names
โ
Avoid building your entire app around dynamic queries
โ
Limit fields and rows - youโre still living in governorland
โ
Use custom metadata to define reusable filter logic for low-code configurability
โ Concatenate user input directly into SOQL strings
โ Skip LIMIT
on large queries
โ Assume object or field names without validation
โ Hardcode fields when your query depends on schema differences
โ Forget governor limits still apply
JUST DONโT BUILD A TREEHOUSE WITH A CHAINSAW
DYNAMIC SOQL IS A POWER TOOL
Dynamic SOQL gives developers superpowers: the ability to craft adaptive queries in a highly declarative platform. ๐ฆธ
But with that power comes risk.
Used responsibly, it unlocks flexible solutions. ๐ช
Used carelessly, it unlocks security holes, governor limit violations, and developer shame. ๐ซข
So go forth, wield your queries wisely, and remember: just because it compiles doesnโt mean itโs safe.
SOUL FOOD
Todayโs Principle
"Programming is the art of telling another human being what one wants the computer to do."
and now....Salesforce Memes



What did you think about today's newsletter? |