๐Ÿ’ƒ 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

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."

Donald Knuth

and now....Salesforce Memes

What did you think about today's newsletter?

Login or Subscribe to participate in polls.