0

I'm a little bit confused. A lot of people suggest using bind variables as params in queries to avoid having SOQL injection. Let's say we have

String name = '%';
String param = '%' + name + '%';
system.debug(param);
String query = 'select name from Account where name like :param';
List<Account> accs = database.query(query);
for(Account a:accs) {
    system.debug(a.Name);
}

It's just an example but we can get name from anywhere we want. But for now i can see all accounts just after setting name up with '%' What's wrong?

2 Answers 2

2

You seem to be mixing the two concepts. SOQL Injection is primarily about injecting an additional SOQL code to your soql query to retrieve additional records For example, your query can be

"select name, phone from account where id = " + accountid

Now, in this example, if someone sends

accountid = "XXX OR createddate > 1999-01-01T00:00:00.000Z"

In this case (without bind variables) the query would become (code is for explanation only)

select name, phone from account where id = XXX OR createddate > 1999-01-01T00:00:00.000Z

Essentially, pulling all account records, which is basically a hack.

Bind variables avoid injecting the additional query clauses, it would result in code to be generated as select name, phone from account where id = 'XXX OR createddate > 1999-01-01T00:00:00.000Z' (treating whole value as one, instead of letting it be treated as two clauses)

Using wildcard (%) in SOQL query with LIKE operator is just standard SOQL functionality.

2
  • so looks like we can provide % as account name in that case and we will get all accounts. cool then. how can we avoid that situation?
    – pincet
    Jul 25, 2021 at 14:39
  • If you want to query just "%" in an account name, yet want to use LIKE, you just need to escape special characters in the account name (not to avoid injection issues but to support the "_", "%" as literal characters). Use backslash to escape, as covered in the documentation.
    – Phil W
    Jul 25, 2021 at 16:49
0

As per documentation

The LIKE operator in SOQL and SOSL supports escaping of special characters % or _.

So when you include % inside %%, it converts that to %%% means all accounts if it has any name and is not empty. And as name cannot be empty it shows everything.

Its same as giving single % or %% or any number of %%%%%%%. because it always matches with any name which is not empty.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .