-
Notifications
You must be signed in to change notification settings - Fork 0
Performing SOQL Queries
To retrieve records from the database using Apex Database Layer, developers can use the Soql class.
Create a new Soql object by calling DatabaseLayer.Soql.newQuery.
Soql employs a builder pattern that allows you to flexibly generate a query that matches your specifications. You can view all of the available query-building methods here.
Once your query is ready to "build", use the toSoql() method to cast the query back to a concrete Soql instance:
Soql query = DatabaseLayer.Soql.newQuery(Account.SObjectType)
?.addSelect(Account.CreatedDate, Account.Name, Account.OwnerId)
?.addWhere(Account.OwnerId, Soql.EQUALS, UserInfo.getUserId())
?.addOrderBy(Account.CreatedDate, Soql.SortDirection.DESCENDING)
?.setRowLimit(1)
?.toSoql();
System.debug(query);
// "SELECT Id, CreatedDate, Name, OwnerId FROM Account WHERE OwnerId = '005000000000000000' ORDER BY CreatedDate DESC LIMIT 1"As shown above, printing the query will output the actual query to be executed.
Call the appropriate method directly from your Soql object to execute a SOQL query, instead of the corresponding Database class methods or inline SOQL queries:
// Don't use these standard query methods:
List<Account> accounts = [SELECT Id, Name FROM Account];
List<Account> accounts = Database.query('SELECT Id, Name FROM Account');
// Use this instead!
List<Account> accounts = (List<Account>) DatabaseLayer.Soql.newQuery(Account.SObjectType)
?.addSelect(Account.Name)
?.toSoql()
?.query();The Soql class supports all Database class query methods. View all Soql methods here.
We recommend using DatabaseLayer.Soql instead of Database methods or inline SOQL queries across your entire codebase. This practice has the following benefits:
- Easily mock SOQL queries in tests with just a couple of lines of code.
-
DatabaseLayer.Soqlcouples the type-safety and referential integrity of inline SOQL queries and the flexibility of "dynamic" string-based queries usingDatabase.query. -
DatabaseLayer.Soqlobjects are easily extendable. You can one query as a "template" for other similar queries.
- Generating Test Records
- Dml
- Soql
- Cmdt
- Plugins
- DatabaseLayer
- Dml
- MockDml
- MockRecord
- Cmdt
- MockCmdt
- MockSoql
-
Soql
- Soql.AggregateResult
- Soql.Aggregation
- Soql.Binder
- Soql.Builder
- Soql.Condition
- Soql.ConditionalLogic
- Soql.Criteria
- Soql.Cursor
- Soql.Function
- Soql.InnerQuery
- Soql.InvalidParameterValueException
- Soql.LogicType
- Soql.NullOrder
- Soql.Operation
- Soql.Operator
- Soql.ParentField
- Soql.PreAndPostProcessor
- Soql.QueryLocator
- Soql.Request
- Soql.Scope
- Soql.Selectable
- Soql.SortDirection
- Soql.SortOrder
- Soql.Subquery
- Soql.TypeOf
- Soql.Usage
- Soql.WhenClause