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

**Topic:** Soql · **Difficulty:** Medium · **Asked at:** Cognizant, Wipro, LTIMindtree · **Tags:** soql, dynamic-soql, apex

Read it on the site: https://www.forcechallenges.com/interview-questions/what-is-dynamic-soql-database-query-and-database-querywithbinds-and-when-do-you-need-it

## Answer

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.

---
Source: ForceChallenges · last updated 2026-10-21
