Development questions

What is Dynamic SOQL (Database.query() and Database.queryWithBinds()) and when do you need it?

DevelopmentMediumCognizantWiproLTIMindtree

Dynamic SOQL builds the query as a string at runtime and runs it with Database.query() or Database.queryWithBinds().

Use it when the object, fields, filters or sort order are not known at compile time (e.g. user-selected filters, generic utilities, field sets).

apex
String q = 'SELECT Id, Name FROM Account WHERE Industry = :ind';
List<Account> accs = Database.query(q);

Map<String, Object> binds = new Map<String, Object>{ 'ind' => 'Tech' };
List<Account> accs2 = Database.queryWithBinds('SELECT Id FROM Account WHERE Industry = :ind', binds, AccessLevel.USER_MODE);

queryWithBinds is safer because bind values are not concatenated into the string.

soqldynamic-soqlapex