QRY_Builder.Builder
Class · Group: Query Infrastructure
Learn it: Fast Start - Selectors and Selectors guide
global virtual inherited sharing class QRY_Builder.Builder implements IF_QueryableImplements: IF_Queryable
Known Derived Types: IF_Queryable.count(), IF_Queryable.exists(), IF_Queryable.getFirst(), IF_Queryable.toList(), IF_Queryable.toQueryLocator()
Extensible query builder class. Maintains internal query state and uses QRY_Generator for SOQL building and QRY_Engine for execution.
Example
QRY_Builder.Builder query = QRY_Builder.selectFrom(Account.SObjectType)
.addField(Account.Name)
.condition(Account.Industry).equals('Technology');
List<Account> accounts = query.toList();Methods by task
Find a method by what you want to do. A group links to a worked example when a guide has one. Every method is described in the full list below.
Methods
| Method | Description |
|---|---|
| global QRY_Builder.Builder addCondition(QRY_Condition.Evaluable condition) | Adds a pre-built condition to the query. |
| global virtual QRY_Builder.Builder addField(QRY_Function functionField, String alias) | Adds a SOQL date-function expression to SELECT under an explicit alias, so you can read it back through AggregateRow (e.g. |
| global QRY_Builder.Builder addField(SObjectField objectField) | Adds a single field without disabling default fields. |
| global QRY_Builder.Builder addField(String fieldName) | Adds a single field without disabling default fields. |
| global QRY_Builder.Builder addFields(List<SObjectField> objectFields) | Adds fields to the selection without disabling default fields. |
| global QRY_Builder.Builder addFields(List<String> fieldNames) | Adds fields to the selection without disabling default fields. |
| global QRY_Builder.Builder addFieldSet(FieldSet aFieldset) | Adds fields from a FieldSet token without disabling default fields. |
| global QRY_Builder.Builder addFieldSet(String fieldSetName) | Adds fields from a FieldSet without disabling default fields. |
| global QRY_Builder.Builder allRows() | Includes deleted and archived records (ALL ROWS). |
| global virtual QRY_Builder.ConditionBuilder andCondition(QRY_Function functionField) | Starts an AND condition whose left-hand side is a SOQL function expression (for example a geolocation DISTANCE from QRY_Function.distanceInMiles). |
| global QRY_Builder.ConditionBuilder andCondition(SObjectField field) | Starts an AND condition on a field using an SObjectField token. |
| global QRY_Builder.ConditionBuilder andCondition(String fieldName) | Starts an AND condition on a field using its API name. |
| global QRY_Builder.Builder ascending() | Sets the last ORDER BY clause to ASCENDING. |
| global Map<Id, List<SObject>> asGroupedMapById(SObjectField keyField) | Executes the query and returns the results grouped by an Id field (e.g. |
| global Map<Id, List<SObject>> asGroupedMapById(String fieldName) | Executes the query and returns the results grouped by an Id field. |
| global Map<String, List<SObject>> asGroupedMapByString(SObjectField keyField) | Executes the query and returns the results grouped by a String field value. |
| global Map<String, List<SObject>> asGroupedMapByString(String fieldName) | Executes the query and returns the results grouped by a String field value. |
| global List<Id> asIdList() | Returns the results as a List of Ids. |
| global Set<Id> asIdSet() | Executes the query and returns a Set of record Ids. |
| global Map<Id, SObject> asMap() | Executes the query and returns results as a Map. |
| global Map<Id, SObject> asMapById(SObjectField keyField) | Executes the query and returns the results as a Map keyed by the specified Id field (e.g. |
| global Map<Id, SObject> asMapById(String fieldName) | Executes the query and returns the results as a Map keyed by the specified Id field. |
| global Map<String, SObject> asMapByString(SObjectField keyField) | Executes the query and returns the results as a Map keyed by a String field value. |
| global Map<String, SObject> asMapByString(String fieldName) | Executes the query and returns the results as a Map keyed by a String field value. |
| global Set<String> asStringSet(SObjectField field) | Executes the query and returns a Set of distinct String values for the specified field. |
| global Set<String> asStringSet(String fieldName) | Executes the query and returns a Set of distinct String values for the specified field. |
| global Set<Object> asValueSet(SObjectField field) | Executes the query and returns a Set of distinct values for the specified field. |
| global Set<Object> asValueSet(String fieldName) | Executes the query and returns a Set of distinct values for the specified field. |
| global QRY_Builder.Builder avg(SObjectField field) | Applies an AVG aggregate function. |
| global virtual QRY_Builder.Builder avg(SObjectField field, String alias) | Applies an AVG aggregate under an explicit result alias. |
| global QRY_Builder.Builder bypassSharing() | Reads records whatever the record sharing, through a without sharing proxy class. |
| global virtual QRY_Builder.ConditionBuilder condition(QRY_Function functionField) | Starts a WHERE condition whose left-hand side is a SOQL function expression (for example a geolocation DISTANCE from QRY_Function.distanceInMiles), so you can filter on the function result: .lessThan(10) renders DISTANCE(...) < 10. |
| global QRY_Builder.ConditionBuilder condition(SObjectField objectField) | Starts a WHERE condition on a field using an SObjectField token. |
| global QRY_Builder.ConditionBuilder condition(String fieldName) | Starts a WHERE condition on a field using its API name. |
| global Integer count() | Returns the number of records that match the query criteria. |
| global virtual QRY_Builder.Builder count(SObjectField field, String alias) | Applies a COUNT aggregate under an explicit result alias. |
| global QRY_Builder.Builder count(String fieldName) | Applies a COUNT aggregate function. |
| global QRY_Builder.Builder countDistinct(SObjectField field) | Applies a COUNT_DISTINCT aggregate function. |
| global virtual QRY_Builder.Builder countDistinct(SObjectField field, String alias) | Applies a COUNT_DISTINCT aggregate under an explicit result alias. |
| global QRY_Builder.Builder countDistinct(String fieldName) | Applies a COUNT_DISTINCT aggregate function. |
| global QRY_Builder.Builder cube() | Flags the GROUP BY clause as CUBE for cross-tabulation. |
| global QRY_Builder.Builder descending() | Sets the last ORDER BY clause to DESCENDING. |
| global Boolean exists() | Checks whether any records exist matching the query criteria. |
| global QRY_Builder.Builder fields(List<SObjectField> objectFields) | Explicitly select fields using SObjectField tokens. |
| global QRY_Builder.Builder fields(List<String> fieldNames) | Explicitly select fields by API name. |
| global QRY_Builder.Builder fieldSet(FieldSet aFieldset) | Selects fields from a FieldSet token. |
| global QRY_Builder.Builder fieldSet(String fieldSetName) | Selects fields from a FieldSet. |
| global QRY_Builder.Builder forcePerformanceLogging() | Forces performance logging regardless of threshold for this query. |
| global QRY_Builder.Builder forReference() | Locks returned records FOR REFERENCE. |
| global QRY_Builder.Builder forUpdate() | Locks returned records FOR UPDATE. |
| global QRY_Builder.Builder forView() | Locks returned records FOR VIEW. |
| global virtual Set<String> getDefaultFields() | Override to provide default fields for this selector. |
| global SObject getFirst() | Executes the query and returns the first record (or null). |
| global QRY_Builder.AggregateRow getFirstAggregate() | Executes an aggregate query and returns the first result as a typed AggregateRow. |
| global QRY_Builder.QueryPage getPage(Integer requestedPageNumber, Integer requestedPageSize) | Executes a paged query and returns results with pagination metadata. |
| global SObject getRandomItem() | Returns a single random record matching the query criteria. |
| global List<SObject> getRandomItems(Integer randomCount) | Returns multiple random records matching the query criteria. |
| global virtual QRY_Builder.Builder groupBy(QRY_Function functionField) | Adds a SOQL date-function expression to the GROUP BY clause (e.g. |
| global QRY_Builder.Builder groupBy(SObjectField groupField) | Adds a field to the GROUP BY clause using an SObjectField token. |
| global QRY_Builder.Builder groupBy(String groupField) | Adds a GROUP BY clause. |
| global QRY_Builder.Builder grouping(SObjectField field) | Adds a GROUPING(field) expression to the SELECT clause for use with ROLLUP or CUBE. |
| global QRY_Builder.Builder grouping(String fieldName) | Adds a GROUPING(field) expression to the SELECT clause by field name. |
| global QRY_Builder.ConditionBuilder havingAvgOf(SObjectField field) | Starts a HAVING condition on the AVG of a field. |
| global QRY_Builder.ConditionBuilder havingCount() | Starts a HAVING condition on the global COUNT(). |
| global QRY_Builder.ConditionBuilder havingCountOf(SObjectField field) | Starts a HAVING condition on the COUNT of a field. |
| global QRY_Builder.ConditionBuilder havingMaxOf(SObjectField field) | Starts a HAVING condition on the MAX of a field. |
| global QRY_Builder.ConditionBuilder havingMinOf(SObjectField field) | Starts a HAVING condition on the MIN of a field. |
| global QRY_Builder.ConditionBuilder havingSumOf(SObjectField field) | Starts a HAVING condition on the SUM of a field. |
| global Boolean isCached() | Indicates whether the last execution retrieved results from cache. |
| global QRY_Builder.Builder logPerformanceIfSlowerThan(Integer thresholdMs) | Sets a custom performance threshold for this query. |
| global QRY_Builder.Builder max(SObjectField field) | Applies a MAX aggregate function. |
| global virtual QRY_Builder.Builder max(SObjectField field, String alias) | Applies a MAX aggregate under an explicit result alias. |
| global QRY_Builder.Builder min(SObjectField field) | Applies a MIN aggregate function. |
| global virtual QRY_Builder.Builder min(SObjectField field, String alias) | Applies a MIN aggregate under an explicit result alias. |
| global QRY_Builder.Builder nullsFirst() | Sets the last ORDER BY clause to NULLS FIRST. |
| global QRY_Builder.Builder nullsLast() | Sets the last ORDER BY clause to NULLS LAST. |
| global virtual QRY_Builder.ConditionBuilder orCondition(QRY_Function functionField) | Starts an OR condition whose left-hand side is a SOQL function expression (for example a geolocation DISTANCE from QRY_Function.distanceInMiles). |
| global QRY_Builder.ConditionBuilder orCondition(SObjectField field) | Starts an OR condition on a field using an SObjectField token. |
| global QRY_Builder.ConditionBuilder orCondition(String fieldName) | Starts an OR condition on a field using its API name. |
| global virtual QRY_Builder.Builder orderBy(QRY_Function functionField) | Orders by a SOQL date-function expression, ascending (e.g. |
| global virtual QRY_Builder.Builder orderBy(QRY_Function functionField, Boolean sortDescending) | Orders by a SOQL date-function expression, ascending or descending. |
| global QRY_Builder.Builder orderBy(SObjectField field) | Adds an ORDER BY clause (default ascending). |
| global QRY_Builder.Builder orderBy(SObjectField field, Boolean sortDescending) | Adds an ORDER BY clause with a dynamic sort direction. |
| global QRY_Builder.Builder orderBy(SObjectField field, Boolean sortDescending, Boolean nullsLast) | Adds an ORDER BY clause with a dynamic sort direction and nulls placement. |
| global QRY_Builder.Builder orderBy(String fieldName) | Adds an ORDER BY clause (default ascending). |
| global QRY_Builder.Builder orderBy(String fieldName, Boolean sortDescending) | Adds an ORDER BY clause with a dynamic sort direction. |
| global QRY_Builder.Builder orderBy(String fieldName, Boolean sortDescending, Boolean nullsLast) | Adds an ORDER BY clause with a dynamic sort direction and nulls placement. |
| global virtual QRY_Builder.Builder orderByCount(SObjectField field, Boolean sortDescending) | Orders an aggregate query by COUNT of a field (e.g. |
| global QRY_Builder.Builder relatedField(String parentField) | Adds a single parent field. |
| global QRY_Builder.Builder relatedFields(List<String> parentFields) | Adds parent (related) fields to the selection. |
| global QRY_Builder.Builder rollup() | Flags the GROUP BY clause as ROLLUP for subtotals. |
| global QRY_Builder.Builder selectAllFields() | Configures the query to select ALL fields on the object. |
| global QRY_Builder.Builder stripInaccessible() | Strips inaccessible fields from results. |
| global QRY_Builder.Builder subselect(QRY_Builder.Builder childQuery, String relationshipName) | Adds a child subquery (child relationship query). |
| global QRY_Builder.Builder sum(SObjectField field) | Applies a SUM aggregate function. |
| global virtual QRY_Builder.Builder sum(SObjectField field, String alias) | Applies a SUM aggregate under an explicit result alias. |
| global QRY_Builder.Builder suppressPerformanceLogging() | Stops this query from writing a performance log entry, even when it is slow. |
| global List<QRY_Builder.AggregateRow> toAggregateList() | Executes an aggregate query and returns results as typed AggregateRow wrappers. |
| global Database.Cursor toCursor() | Returns a Database.Cursor for reading a large set of records in parts. |
| global List<SObject> toList() | Executes the query and returns a List of SObjects. |
| global Database.QueryLocator toQueryLocator() | Returns a Database.QueryLocator for batch processing. |
| global String toSoql() | Generates and returns the SOQL string without executing it. |
| global QRY_Builder.Builder usingScope(QRY_Builder.Scope scopeValue) | Filters records by visibility scope using USING SCOPE clause. |
| global QRY_Builder.Builder withCache(Integer ttlSeconds) | Enables caching for this query. |
| global virtual QRY_Builder.Builder withCache(UTIL_Cache.Scope scope, Integer ttlSeconds) | Caches this query's results in the given scope. |
| global QRY_Builder.DataCategoryBuilder withDataCategory(String groupName) | Starts a WITH DATA CATEGORY filter for the specified data category group. |
| global QRY_Builder.Builder withLimit(Integer recordLimit) | Sets the maximum number of records to return (LIMIT). |
| global QRY_Builder.Builder withOffset(Integer rowNumber) | Sets the record offset (OFFSET). |
| global virtual QRY_Builder.Builder withoutCache() | Makes this query read from the database, whatever caching the selector or an earlier call asked for. |
| global QRY_Builder.Builder withoutSecurity() | Turns off every security check the builder controls, in one call. |
| global QRY_Builder.Builder withSharing() | Enforces sharing rules using a with sharing proxy class. |
| global QRY_Builder.Builder withSystemMode() | Runs the query in SYSTEM_MODE, whatever the UserModeQueries_Enabled feature flag says. |
| global QRY_Builder.Builder withUserMode() | Runs the query in USER_MODE. |
addCondition
global QRY_Builder.Builder addCondition(QRY_Condition.Evaluable condition)Adds a pre-built condition to the query. Use this for complex condition groups that cannot be expressed with the fluent API.
Parameters
| Parameter | Type | Description |
|---|---|---|
condition | QRY_Condition.Evaluable | The condition to add (created via QRY_Condition classes) |
Returns QRY_Builder.Builder — Builder for chaining
Example
QRY_Condition.OrCondition statusGroup = new QRY_Condition.OrCondition();
statusGroup.add(new QRY_Condition.FieldCondition('Status__c', QRY_Condition.Operator.EQUALS, 'Active'));
statusGroup.add(new QRY_Condition.FieldCondition('Status__c', QRY_Condition.Operator.EQUALS, 'Pending'));
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Industry).equals('Technology')
.addCondition(statusGroup)
.toList();addField
global virtual QRY_Builder.Builder addField(QRY_Function functionField, String alias)Adds a SOQL date-function expression to SELECT under an explicit alias, so you can read it back through AggregateRow (e.g. CALENDAR_MONTH(CloseDate) closeMonth, then row.getInteger('closeMonth')). Use it with groupBy(QRY_Function) and the same factory, so the SELECT and GROUP BY expressions match. The alias must be a plain name, the same rule as for the aliased aggregate selections, so an alias a caller supplies can never add SOQL syntax to the clause.
Parameters
| Parameter | Type | Description |
|---|---|---|
functionField | QRY_Function | The date-function expression, from a QRY_Function factory |
alias | String | The read-back alias for the projected expression; must be a bare identifier |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if alias is not a bare identifier (a letter followed by letters, digits or underscores) |
Example
QRY_Builder.selectFrom(Opportunity.SObjectType)
.addField(QRY_Function.calendarMonth(Opportunity.CloseDate), 'closeMonth')
.count('Id')
.groupBy(QRY_Function.calendarMonth(Opportunity.CloseDate))
.toAggregateList();global QRY_Builder.Builder addField(SObjectField objectField)Adds a single field without disabling default fields.
Parameters
| Parameter | Type | Description |
|---|---|---|
objectField | SObjectField | SObjectField token |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.addField(Account.Website)
.toList();global QRY_Builder.Builder addField(String fieldName)Adds a single field without disabling default fields.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | API name |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.addField('Website')
.toList();addFields
global QRY_Builder.Builder addFields(List<SObjectField> objectFields)Adds fields to the selection without disabling default fields.
Parameters
| Parameter | Type | Description |
|---|---|---|
objectFields | List | List of SObjectField tokens |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.addFields(new List<SObjectField>{Account.Phone, Account.Website})
.toList();global QRY_Builder.Builder addFields(List<String> fieldNames)Adds fields to the selection without disabling default fields.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldNames | List | List of field API names |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.addFields(new List<String>{'Phone', 'Website'})
.toList();addFieldSet
global QRY_Builder.Builder addFieldSet(FieldSet aFieldset)Adds fields from a FieldSet token without disabling default fields.
Parameters
| Parameter | Type | Description |
|---|---|---|
aFieldset | FieldSet | The Schema.FieldSet token |
Returns QRY_Builder.Builder — Builder for chaining
Example
FieldSet fs = SObjectType.Account.fieldSets.Account_Summary;
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.addFieldSet(fs)
.toList();global QRY_Builder.Builder addFieldSet(String fieldSetName)Adds fields from a FieldSet without disabling default fields.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldSetName | String | The API Name of the FieldSet |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.addFieldSet('Account_Summary')
.toList();allRows
global QRY_Builder.Builder allRows()Includes deleted and archived records (ALL ROWS).
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.IsDeleted).equals(true)
.allRows()
.toList();andCondition
global virtual QRY_Builder.ConditionBuilder andCondition(QRY_Function functionField)Starts an AND condition whose left-hand side is a SOQL function expression (for example a geolocation DISTANCE from QRY_Function.distanceInMiles). Mirrors andCondition(SObjectField) for function expressions.
Parameters
| Parameter | Type | Description |
|---|---|---|
functionField | QRY_Function | The function expression, from a QRY_Function factory |
Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator
Example
List<Account> nearby = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Industry).equals('Technology')
.andCondition(QRY_Function.distanceInMiles(Account.BillingAddress, 37.775, -122.418)).lessThan(10)
.toList();global QRY_Builder.ConditionBuilder andCondition(SObjectField field)Starts an AND condition on a field using an SObjectField token.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | Field token |
Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Industry).equals('Technology')
.andCondition(Account.Type).equals('Customer')
.toList();global QRY_Builder.ConditionBuilder andCondition(String fieldName)Starts an AND condition on a field using its API name. The text may also be a date or distance function from QRY_Function, or toLabel around a field name. Text that comes from a page or a user must first be matched to a field through a list of fields you allow.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | A field API name, such as Name or Account.Owner.Name |
Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if the text is not blank and is not a field name |
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.condition('Industry').equals('Technology')
.andCondition('Type').equals('Customer')
.toList();ascending
global QRY_Builder.Builder ascending()Sets the last ORDER BY clause to ASCENDING.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.orderBy(Account.Name).ascending()
.toList();asGroupedMapById
global Map<Id, List<SObject>> asGroupedMapById(SObjectField keyField)Executes the query and returns the results grouped by an Id field (e.g. a parent-lookup field). Duplicates are preserved as separate entries within each group. Delegates to UTIL_SObject.groupByKey.
Parameters
| Parameter | Type | Description |
|---|---|---|
keyField | SObjectField | The SObjectField token whose value will be used as the map key. Must reference an Id-typed field on the returned SObject. |
Returns SObject — Map > keyed by the field value. Records with a null key field are grouped under the null key. Returns an empty map if the query yields no results.
Example
Map<Id, List<SObject>> contactsByAccount = QRY_Builder.selectFrom(Contact.SObjectType)
.addFields(new List<SObjectField>{Contact.Id, Contact.AccountId})
.condition(Contact.AccountId).isNotNull()
.asGroupedMapById(Contact.AccountId);global Map<Id, List<SObject>> asGroupedMapById(String fieldName)Executes the query and returns the results grouped by an Id field. Supports dot-notation for parent fields. Delegates to UTIL_SObject.groupByKey.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | The API name of the Id field whose value will be used as the map key. |
Returns SObject — Map > keyed by the field value. Records with a null key field are grouped under the null key. Returns an empty map when the query yields no results.
Example
Map<Id, List<SObject>> contactsByOwner = QRY_Builder.selectFrom(Contact.SObjectType)
.addField(Contact.OwnerId)
.asGroupedMapById('OwnerId');asGroupedMapByString
global Map<String, List<SObject>> asGroupedMapByString(SObjectField keyField)Executes the query and returns the results grouped by a String field value. Duplicates are preserved as separate entries within each group. Key casing is preserved. Delegates to UTIL_SObject.groupByStringKey.
Parameters
| Parameter | Type | Description |
|---|---|---|
keyField | SObjectField | The SObjectField token whose value will be used as the map key. |
Returns SObject — Map > keyed by the stringified field value. Returns an empty map when the query yields no results.
Example
Map<String, List<SObject>> accountsByIndustry = QRY_Builder.selectFrom(Account.SObjectType)
.addField(Account.Industry)
.asGroupedMapByString(Account.Industry);global Map<String, List<SObject>> asGroupedMapByString(String fieldName)Executes the query and returns the results grouped by a String field value. Supports dot-notation for parent fields. Key casing is preserved. Delegates to UTIL_SObject.groupByStringKey.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | The API name of the field whose value will be used as the map key. |
Returns SObject — Map > keyed by the stringified field value. Returns an empty map when the query yields no results.
Example
Map<String, List<SObject>> accountsByOwnerName = QRY_Builder.selectFrom(Account.SObjectType)
.addField(Account.OwnerId)
.relatedField('Owner.Name')
.asGroupedMapByString('Owner.Name');asIdList
global List<Id> asIdList()Returns the results as a List of Ids.
Returns Id — List
Example
List<Id> accountIds = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Type).equals('Customer')
.asIdList();asIdSet
global Set<Id> asIdSet()Executes the query and returns a Set of record Ids.
Returns Id — Set
Example
Set<Id> accountIds = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Type).equals('Customer')
.asIdSet();asMap
global Map<Id, SObject> asMap()Executes the query and returns results as a Map .
Returns SObject — Map
Example
Map<Id, SObject> accountMap = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Type).equals('Customer')
.asMap();asMapById
global Map<Id, SObject> asMapById(SObjectField keyField)Executes the query and returns the results as a Map keyed by the specified Id field (e.g. a parent-lookup field). Last record wins when key values collide. Delegates to UTIL_SObject.indexById.
Parameters
| Parameter | Type | Description |
|---|---|---|
keyField | SObjectField | The SObjectField token whose value will be used as the map key. Must reference an Id-typed field on the returned SObject. |
Returns SObject — Map keyed by the field value. Records with a null key field are mapped under the null key. Returns an empty map when the query yields no results.
Example
Map<Id, SObject> contactsByAccount = QRY_Builder.selectFrom(Contact.SObjectType)
.addFields(new List<SObjectField>{Contact.Id, Contact.AccountId})
.condition(Contact.AccountId).isNotNull()
.asMapById(Contact.AccountId);global Map<Id, SObject> asMapById(String fieldName)Executes the query and returns the results as a Map keyed by the specified Id field. Supports dot-notation for parent fields (e.g. 'Account.OwnerId'). Delegates to UTIL_SObject.indexById.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | The API name of the Id field whose value will be used as the map key. |
Returns SObject — Map keyed by the field value. Records with a null key field are mapped under the null key. Returns an empty map when the query yields no results.
Example
Map<Id, SObject> contactsByOwner = QRY_Builder.selectFrom(Contact.SObjectType)
.addField(Contact.OwnerId)
.asMapById('OwnerId');asMapByString
global Map<String, SObject> asMapByString(SObjectField keyField)Executes the query and returns the results as a Map keyed by a String field value. Last record wins when key values collide. Key casing is preserved (no implicit lowering). Delegates to UTIL_SObject.indexByStringKey.
Parameters
| Parameter | Type | Description |
|---|---|---|
keyField | SObjectField | The SObjectField token whose value will be used as the map key. |
Returns SObject — Map keyed by the stringified field value. Returns an empty map when the query yields no results.
Example
Map<String, SObject> accountByName = QRY_Builder.selectFrom(Account.SObjectType)
.addField(Account.Name)
.asMapByString(Account.Name);global Map<String, SObject> asMapByString(String fieldName)Executes the query and returns the results as a Map keyed by a String field value. Supports dot-notation for parent fields (e.g. 'Owner.Name'). Key casing is preserved. Delegates to UTIL_SObject.indexByStringKey.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | The API name of the field whose value will be used as the map key. |
Returns SObject — Map keyed by the stringified field value. Returns an empty map when the query yields no results.
Example
Map<String, SObject> accountByOwnerName = QRY_Builder.selectFrom(Account.SObjectType)
.addField(Account.OwnerId)
.relatedField('Owner.Name')
.asMapByString('Owner.Name');asStringSet
global Set<String> asStringSet(SObjectField field)Executes the query and returns a Set of distinct String values for the specified field.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field token to extract String values from |
Returns String — Set of String field values (nulls excluded)
Example
Set<String> nicknames = QRY_Builder.selectFrom(User.SObjectType)
.addField(User.CommunityNickname)
.condition(User.CommunityNickname).startsWith('Billy')
.asStringSet(User.CommunityNickname);global Set<String> asStringSet(String fieldName)Executes the query and returns a Set of distinct String values for the specified field.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | The field API name to extract String values from |
Returns String — Set of String field values (nulls excluded)
Example
Set<String> ownerNames = QRY_Builder.selectFrom(Account.SObjectType)
.relatedField('Owner.Name')
.asStringSet('Owner.Name');asValueSet
global Set<Object> asValueSet(SObjectField field)Executes the query and returns a Set of distinct values for the specified field.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field token to extract values from |
Returns Object — Set of field values
Example
Set<Object> industries = QRY_Builder.selectFrom(Account.SObjectType)
.addField(Account.Industry)
.asValueSet(Account.Industry);global Set<Object> asValueSet(String fieldName)Executes the query and returns a Set of distinct values for the specified field.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | The field API name to extract values from |
Returns Object — Set of field values
Example
Set<Object> ownerNames = QRY_Builder.selectFrom(Account.SObjectType)
.relatedField('Owner.Name')
.asValueSet('Owner.Name');avg
global QRY_Builder.Builder avg(SObjectField field)Applies an AVG aggregate function.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to aggregate |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Opportunity.SObjectType)
.groupBy(Opportunity.StageName)
.avg(Opportunity.Amount)
.toAggregateList();
Decimal firstStageAverage = rows[0].getDecimal('avg_Amount');global virtual QRY_Builder.Builder avg(SObjectField field, String alias)Applies an AVG aggregate under an explicit result alias. Aliased aggregates add up, so one query can combine several aggregates and read each back by its alias.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to average |
alias | String | The result alias; must be a bare identifier, unique across the aliased selections |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if alias is not a bare identifier (a letter followed by letters, digits or underscores); or, when the query builds, if the alias duplicates an earlier aliased selection |
Example
.avg(Opportunity.Amount, 'meanAmount')bypassSharing
global QRY_Builder.Builder bypassSharing()Reads records whatever the record sharing, through a without sharing proxy class. The call is recorded in the bypass audit when the query runs.
Under user mode (the UserModeQueries_Enabled flag on, or withUserMode()) the running user's object and field permissions still apply:
a user who cannot read the object is refused with a QueryException;
fields the user cannot read are removed from the rows, in parent fields and child rows too, and are not reported;
a filter or a sort on a field that the user cannot read is refused. This covers a field of the queried object, a field inside a function (a date function such as
CALENDAR_YEAR(),convertTimezone()inside one,toLabel()orDISTANCE(), written as text or from QRY_Function), and a path through parent records such asParent__r.Email__c, up to five parents deep: the user must be able to read each parent object on the path, each lookup on the path and the last field. A path through a parent object the user cannot read is refused with a QueryException;a lookup that can point to more than one object, such as
What,WhoorOwner, is read through a shared Name record, and is checked as user mode checks it: the user must be able to read the lookup, such asWhatId, and the field of the Name record, such asNameinWhat.Name. The objects the lookup points to are not checked;for some users Salesforce hides the
ProfileId,UserRoleIdandRecordTypeIdfields of the Name record, so a filter onWhat.ProfileIdor onWhat.RecordType.Nameis refused for them;because the read ignores sharing, a filter on
What.Namecovers every activity in the org. It can find, by name, a record on an object the user cannot open, the first and last name of a contact or a lead, and the company of a lead;a read of rows that selects a path through a lookup the user cannot read, or through a parent object the user cannot read, is refused, as user mode refuses it. This covers
What.Namewithout read onWhatId,Account.Nameon a contact without read on Account, child queries, andTYPEOF, whose relationship and each object afterWHENmust be readable;in the selected fields, a hidden lookup gives a UTIL_Exceptions.IllegalStateException, and a hidden parent object gives a QueryException. A hidden last field, such as
PhoneinAccount.Phone, is not refused: it is removed from the rows;selected text the builder cannot check is refused with a UTIL_Exceptions.IllegalStateException, even when the user can read everything in it. Each selected field must be a field name or a path such as
Account.Name, with or without a function around it. So add a child query with subselect(), not as text, and write eachTYPEOFas a field of its own:TYPEOF What WHEN Account THEN Name, Phone ELSE Name END;a query inside isIn() or notIn() is checked the same way, on its own object, and so is a child query added with subselect(), on the object its relationship reads: the user must be able to read that object and the fields it filters or sorts on. A child query built for another object is checked as the object SOQL reads through the relationship;
a child query added with subselect() is refused when the user cannot read the lookup behind its relationship, such as
WhatIdfor theEventsof an account, as user mode refuses it, even when the child query selects onlyId. Some objects use one relationship name for two lookups; then the user must be able to read both. A relationship name the parent object does not have is refused too. The name may start with the parent object, as inAccount.Contacts, as SOQL allows. count() and exists() do not read the child query, so they refuse neither of these;toQueryLocator(), toCursor() and every total or group read (toAggregateList(), getFirstAggregate(), or a grouped query read as records) are refused, because their rows cannot be cleaned;
getPage() returns a page with a null cursor, for the same reason.
A filter in your own Evaluable is not checked. Its rows can tell the user something about that field, so do not filter on a field the user cannot read that way.
To read a locator, a cursor or totals without sharing, add withSystemMode(). withSystemMode() also turns off the object and field permission checks for the read. With the UserModeQueries_Enabled flag off, a read runs in system mode, so nothing is checked, as for any read.
Returns QRY_Builder.Builder — Builder for chaining
Example
// Reads every open case, whoever owns it. Fields the user cannot read are removed from the rows.
List<Case> openCases = QRY_Builder.selectFrom(Case.SObjectType)
.condition(Case.IsClosed).equals(false)
.bypassSharing()
.toList();// A batch job's locator needs withSystemMode() too, which also turns off the field checks.
Database.QueryLocator locator = QRY_Builder.selectFrom(Case.SObjectType)
.withSystemMode()
.bypassSharing()
.toQueryLocator();condition
global virtual QRY_Builder.ConditionBuilder condition(QRY_Function functionField)Starts a WHERE condition whose left-hand side is a SOQL function expression (for example a geolocation DISTANCE from QRY_Function.distanceInMiles), so you can filter on the function result: .lessThan(10) renders DISTANCE(...) < 10. Mirrors condition(SObjectField) but seats the rendered function expression on the comparison left-hand side.
Parameters
| Parameter | Type | Description |
|---|---|---|
functionField | QRY_Function | The function expression, from a QRY_Function factory |
Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator
Example
List<Account> nearby = QRY_Builder.selectFrom(Account.SObjectType)
.condition(QRY_Function.distanceInMiles(Account.BillingAddress, 37.775, -122.418)).lessThan(10)
.toList();global QRY_Builder.ConditionBuilder condition(SObjectField objectField)Starts a WHERE condition on a field using an SObjectField token.
Parameters
| Parameter | Type | Description |
|---|---|---|
objectField | SObjectField | Field token |
Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Industry).equals('Technology')
.toList();global QRY_Builder.ConditionBuilder condition(String fieldName)Starts a WHERE condition on a field using its API name. The text may also be a date or distance function from QRY_Function, or toLabel around a field name. Text that comes from a page or a user must first be matched to a field through a list of fields you allow.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | A field API name, such as Name or Account.Owner.Name |
Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if the text is not blank and is not a field name |
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.condition('Industry').equals('Technology')
.toList();count
global Integer count()Returns the number of records that match the query criteria.
The count does not read a child query added with subselect(). So with bypassSharing() alone, under user mode, the lookup behind a child query is not checked, and a relationship name the parent object does not have is not refused. When the relationship is found, the object it reads and the filters and sorts of the child query are still checked. When it is not found, the child query is not checked at all.
Returns Integer — Integer count
Throws
| Exception | Description |
|---|---|
| QueryException | With bypassSharing() alone, under user mode, when the running user cannot read the object, or the object of a query inside isIn(), notIn() or subselect(). |
| UTIL_Exceptions.IllegalStateException | With bypassSharing() alone, under user mode, when the query is an aggregate query, or when it filters or sorts on a field the running user cannot read. Add withSystemMode(). |
Example
Integer total = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Type).equals('Customer')
.count();global virtual QRY_Builder.Builder count(SObjectField field, String alias)Applies a COUNT aggregate under an explicit result alias. Aliased aggregates add up: unlike the overloads without an alias, each call adds one more selection. So one query can combine several aggregates and read each back by its alias on the AggregateRow.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to count |
alias | String | The result alias; must be a bare identifier, unique across the aliased selections |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if alias is not a bare identifier (a letter followed by letters, digits or underscores); or, when the query builds, if the alias duplicates an earlier aliased selection |
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Opportunity.SObjectType)
.groupBy(Opportunity.StageName)
.count(Opportunity.Id, 'rowTotal')
.min(Opportunity.CreatedDate, 'firstSeen')
.toAggregateList();global QRY_Builder.Builder count(String fieldName)Applies a COUNT aggregate function. Text that comes from a page or a user must first be matched to a field through a list of fields you allow.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | A field API name, such as Name or Account.Owner.Name (or null for COUNT()) |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if the text is not blank and is not a field name or a path through parent records, such as Account.Owner.Name |
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Account.SObjectType)
.groupBy(Account.Industry)
.count('Id')
.toAggregateList();
Integer firstIndustryCount = rows[0].getInteger('count_Id');countDistinct
global QRY_Builder.Builder countDistinct(SObjectField field)Applies a COUNT_DISTINCT aggregate function.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to count distinct values |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Contact.SObjectType)
.groupBy(Contact.AccountId)
.countDistinct(Contact.Email)
.toAggregateList();
Integer firstAccountEmailCount = rows[0].getInteger('count_distinct_Email');global virtual QRY_Builder.Builder countDistinct(SObjectField field, String alias)Applies a COUNT_DISTINCT aggregate under an explicit result alias. Aliased aggregates add up, so one query can combine several aggregates and read each back by its alias.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to count distinct values of |
alias | String | The result alias; must be a bare identifier, unique across the aliased selections |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if alias is not a bare identifier (a letter followed by letters, digits or underscores); or, when the query builds, if the alias duplicates an earlier aliased selection |
Example
.countDistinct(Contact.Email, 'uniqueEmails')global QRY_Builder.Builder countDistinct(String fieldName)Applies a COUNT_DISTINCT aggregate function. Text that comes from a page or a user must first be matched to a field through a list of fields you allow.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | A field API name, such as Name or Account.Owner.Name |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if the text is not blank and is not a field name or a path through parent records, such as Account.Owner.Name |
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Contact.SObjectType)
.groupBy(Contact.AccountId)
.countDistinct('Email')
.toAggregateList();
Integer firstAccountEmailCount = rows[0].getInteger('count_distinct_Email');cube
global QRY_Builder.Builder cube()Flags the GROUP BY clause as CUBE for cross-tabulation.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<QRY_Builder.AggregateRow> results = QRY_Builder.selectFrom(Opportunity.SObjectType)
.groupBy(Opportunity.StageName)
.groupBy(Opportunity.LeadSource)
.sum(Opportunity.Amount)
.cube()
.toAggregateList();descending
global QRY_Builder.Builder descending()Sets the last ORDER BY clause to DESCENDING.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.orderBy(Account.CreatedDate).descending()
.toList();exists
global Boolean exists()Checks whether any records exist matching the query criteria.
It counts the records as count() does, so with bypassSharing() alone it checks a child query added with subselect() the way count() does: the lookup behind it is not checked, and a relationship name the parent object does not have is not refused.
Returns Boolean — Boolean true if at least one record exists
Throws
| Exception | Description |
|---|---|
| QueryException | With bypassSharing() alone, under user mode, when the running user cannot read the object, or the object of a query inside isIn(), notIn() or subselect(). |
| UTIL_Exceptions.IllegalStateException | With bypassSharing() alone, under user mode, when the query is an aggregate query, or when it filters or sorts on a field the running user cannot read. Add withSystemMode(). |
Example
Boolean hasCustomers = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Type).equals('Customer')
.exists();fields
global QRY_Builder.Builder fields(List<SObjectField> objectFields)Explicitly select fields using SObjectField tokens.
Parameters
| Parameter | Type | Description |
|---|---|---|
objectFields | List | List of SObjectField tokens |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<SObjectField>{Account.Name, Account.Industry})
.toList();global QRY_Builder.Builder fields(List<String> fieldNames)Explicitly select fields by API name.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldNames | List | List of field API names |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry', 'AnnualRevenue'})
.toList();fieldSet
global QRY_Builder.Builder fieldSet(FieldSet aFieldset)Selects fields from a FieldSet token.
Parameters
| Parameter | Type | Description |
|---|---|---|
aFieldset | FieldSet | The Schema.FieldSet token |
Returns QRY_Builder.Builder — Builder for chaining
Example
FieldSet fs = SObjectType.Account.fieldSets.Account_Summary;
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fieldSet(fs)
.toList();global QRY_Builder.Builder fieldSet(String fieldSetName)Selects fields from a FieldSet.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldSetName | String | The API Name of the FieldSet |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fieldSet('Account_Summary')
.toList();forcePerformanceLogging
global QRY_Builder.Builder forcePerformanceLogging()Forces performance logging regardless of threshold for this query.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.forcePerformanceLogging()
.toList();forReference
global QRY_Builder.Builder forReference()Locks returned records FOR REFERENCE.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Id).equals(accountId)
.forReference()
.toList();forUpdate
global QRY_Builder.Builder forUpdate()Locks returned records FOR UPDATE.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Id).equals(accountId)
.forUpdate()
.toList();forView
global QRY_Builder.Builder forView()Locks returned records FOR VIEW.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Id).equals(accountId)
.forView()
.toList();getDefaultFields
global virtual Set<String> getDefaultFields()Override to provide default fields for this selector.
Returns String — Set of field API names
Example
public override Set<String> getDefaultFields()
{
return new Set<String>{'Name', 'Industry', 'Type'};
}getFirst
global SObject getFirst()Executes the query and returns the first record (or null).
Returns SObject — Single SObject or null
Example
Account account = (Account)QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Id).equals(accountId)
.getFirst();getFirstAggregate
global QRY_Builder.AggregateRow getFirstAggregate()Executes an aggregate query and returns the first result as a typed AggregateRow. Convenience method for single-row aggregates (e.g., SUM without GROUP BY).
Returns QRY_Builder.AggregateRow — Single AggregateRow or null if no results
Throws
| Exception | Description |
|---|---|
| QueryException | With bypassSharing() alone, under user mode, when the running user cannot read the object, or the object of a query inside isIn(), notIn() or subselect(). |
| UTIL_Exceptions.IllegalStateException | With bypassSharing() alone, under user mode: totals and group values cannot have the fields the running user cannot read removed. Add withSystemMode(). |
Example
QRY_Builder.AggregateRow row = QRY_Builder.selectFrom(Opportunity.SObjectType)
.sum(Opportunity.Amount, 'totalAmount')
.getFirstAggregate();
Decimal totalAmount = row.getDecimal('totalAmount');getPage
global QRY_Builder.QueryPage getPage(Integer requestedPageNumber, Integer requestedPageSize)Executes a paged query and returns results with pagination metadata.
A page may hold at most 2,000 records, which is all a cursor will hand back in one fetch.
With bypassSharing() alone, under user mode, the page has no cursor: cursor is null. Rows read later from that cursor would keep the fields the user cannot read, so it is not handed back. records, totalRecords and the paging flags stay correct. Ask for each later page with getPage().
Parameters
| Parameter | Type | Description |
|---|---|---|
requestedPageNumber | Integer | The page number to retrieve (1-based) |
requestedPageSize | Integer | Number of records per page, from 1 to 2000 |
Returns QRY_Builder.QueryPage — Page containing records and pagination metadata
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | When the page number is below 1, or the page size is outside 1 to 2000 |
| QueryException | With bypassSharing() alone, under user mode, when the running user cannot read the object, the object of a query inside isIn(), notIn() or subselect(), or a parent object on a selected path. |
| UTIL_Exceptions.IllegalStateException | When the transaction has used up its cursors (about fifty paged reads in one transaction that could not use a pagination cursor), and the requested page also starts past the 2,000-row offset a plain query can reach. Spread the paged reads across transactions, or narrow the query. Also with bypassSharing() alone, under user mode, when the query is an aggregate query, when it filters or sorts on a field the running user cannot read, when it selects a path or adds a child query through a lookup the running user cannot read, or when it selects text the builder cannot check, such as a child query written as text. Add withSystemMode(). |
Example
QRY_Builder.QueryPage page = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Type).equals('Customer')
.orderBy(Account.Name).ascending()
.getPage(2, 25);getRandomItem
global SObject getRandomItem()Returns a single random record matching the query criteria.
Returns SObject — Single random SObject or null
Example
Account random = (Account)QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Type).equals('Customer')
.getRandomItem();getRandomItems
global List<SObject> getRandomItems(Integer randomCount)Returns multiple random records matching the query criteria. Uses a Database.Cursor to fetch records at a random offset, eliminating the 2,000 SOQL OFFSET limitation. Supports random selection across the full result set (up to 50 million records).
When mocks are active, falls back to standard SOQL OFFSET (capped at 2,000).
With stripInaccessible() on, the fields the running user cannot read are removed from the records, as in toList().
Parameters
| Parameter | Type | Description |
|---|---|---|
randomCount | Integer | Maximum number of random records to return |
Returns SObject — List of random SObjects
Throws
| Exception | Description |
|---|---|
| QueryException | With bypassSharing() alone, under user mode, when the running user cannot read the object, the object of a query inside isIn(), notIn() or subselect(), or a parent object on a selected path. |
| UTIL_Exceptions.IllegalStateException | In a test, when the query is an aggregate query and aggregate rows are registered for the object type. Read such a query with toAggregateList(). Also with bypassSharing() alone, under user mode, when the query is an aggregate query, when it filters or sorts on a field the running user cannot read, when it selects a path or adds a child query through a lookup the running user cannot read, or when it selects text the builder cannot check, such as a child query written as text. Add withSystemMode(). |
Example
List<Account> randoms = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Type).equals('Customer')
.getRandomItems(5);groupBy
global virtual QRY_Builder.Builder groupBy(QRY_Function functionField)Adds a SOQL date-function expression to the GROUP BY clause (e.g. CALENDAR_MONTH(CloseDate)), bucketing records by that date part. Use the same QRY_Function factory in addField to project the bucket.
Parameters
| Parameter | Type | Description |
|---|---|---|
functionField | QRY_Function | The date-function expression, from a QRY_Function factory |
Returns QRY_Builder.Builder — Builder for chaining
Example
QRY_Builder.selectFrom(Opportunity.SObjectType)
.addField(QRY_Function.calendarMonth(Opportunity.CloseDate), 'closeMonth')
.count('Id')
.groupBy(QRY_Function.calendarMonth(Opportunity.CloseDate))
.toAggregateList();global QRY_Builder.Builder groupBy(SObjectField groupField)Adds a field to the GROUP BY clause using an SObjectField token. Call it more than once to group by several fields (SOQL allows at most 3).
Parameters
| Parameter | Type | Description |
|---|---|---|
groupField | SObjectField | The field to group by |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<QRY_Builder.AggregateRow> results = QRY_Builder.selectFrom(Account.SObjectType)
.groupBy(Account.Industry)
.groupBy(Account.Rating)
.count('Id')
.toAggregateList();global QRY_Builder.Builder groupBy(String groupField)Adds a GROUP BY clause. The text is kept as given. It may be one field or several joined by commas, and each may be a date function from QRY_Function. Text that comes from a page or a user must first be matched to a field through a list of fields you allow.
Parameters
| Parameter | Type | Description |
|---|---|---|
groupField | String | A field API name, such as Name or Account.Owner.Name, or a list such as Name, Industry |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if the text is not blank and is not a list of field names or date functions |
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Account.SObjectType)
.groupBy('Industry')
.count('Id')
.toAggregateList();
Integer firstIndustryCount = rows[0].getInteger('count_Id');grouping
global QRY_Builder.Builder grouping(SObjectField field)Adds a GROUPING(field) expression to the SELECT clause for use with ROLLUP or CUBE. Returns 1 for subtotal rows and 0 for regular data rows.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to wrap in GROUPING() |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<QRY_Builder.AggregateRow> results = QRY_Builder.selectFrom(Opportunity.SObjectType)
.groupBy(Opportunity.StageName)
.grouping(Opportunity.StageName)
.sum(Opportunity.Amount)
.rollup()
.toAggregateList();global QRY_Builder.Builder grouping(String fieldName)Adds a GROUPING(field) expression to the SELECT clause by field name. Text that comes from a page or a user must first be matched to a field through a list of fields you allow.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | A field API name, such as Name or Account.Owner.Name, or a date function from QRY_Function |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if the text is not blank and is not a field name or a date function |
Example
.groupBy('Industry').grouping('Industry').rollup()havingAvgOf
global QRY_Builder.ConditionBuilder havingAvgOf(SObjectField field)Starts a HAVING condition on the AVG of a field.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to aggregate |
Returns QRY_Builder.ConditionBuilder — ConditionBuilder configured for HAVING
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Opportunity.SObjectType)
.groupBy(Opportunity.AccountId)
.avg(Opportunity.Amount)
.havingAvgOf(Opportunity.Amount).greaterThan(50000)
.toAggregateList();
Decimal firstAccountAverage = rows[0].getDecimal('avg_Amount');havingCount
global QRY_Builder.ConditionBuilder havingCount()Starts a HAVING condition on the global COUNT().
Returns QRY_Builder.ConditionBuilder — ConditionBuilder configured for HAVING
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Contact.SObjectType)
.groupBy(Contact.AccountId)
.count('Id')
.havingCount().greaterThan(5)
.toAggregateList();
Integer firstAccountContactCount = rows[0].getInteger('count_Id');havingCountOf
global QRY_Builder.ConditionBuilder havingCountOf(SObjectField field)Starts a HAVING condition on the COUNT of a field.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to count |
Returns QRY_Builder.ConditionBuilder — ConditionBuilder configured for HAVING
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Contact.SObjectType)
.groupBy(Contact.AccountId)
.count('Id')
.havingCountOf(Contact.Id).greaterThan(10)
.toAggregateList();
Integer firstAccountContactCount = rows[0].getInteger('count_Id');havingMaxOf
global QRY_Builder.ConditionBuilder havingMaxOf(SObjectField field)Starts a HAVING condition on the MAX of a field.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to aggregate |
Returns QRY_Builder.ConditionBuilder — ConditionBuilder configured for HAVING
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Opportunity.SObjectType)
.groupBy(Opportunity.AccountId)
.max(Opportunity.Amount)
.havingMaxOf(Opportunity.Amount).lessThan(1000000)
.toAggregateList();
Decimal firstAccountLargest = rows[0].getDecimal('max_Amount');havingMinOf
global QRY_Builder.ConditionBuilder havingMinOf(SObjectField field)Starts a HAVING condition on the MIN of a field.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to aggregate |
Returns QRY_Builder.ConditionBuilder — ConditionBuilder configured for HAVING
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Opportunity.SObjectType)
.groupBy(Opportunity.AccountId)
.min(Opportunity.Amount)
.havingMinOf(Opportunity.Amount).greaterThan(1000)
.toAggregateList();
Decimal firstAccountSmallest = rows[0].getDecimal('min_Amount');havingSumOf
global QRY_Builder.ConditionBuilder havingSumOf(SObjectField field)Starts a HAVING condition on the SUM of a field.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to aggregate |
Returns QRY_Builder.ConditionBuilder — ConditionBuilder configured for HAVING
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Opportunity.SObjectType)
.groupBy(Opportunity.AccountId)
.sum(Opportunity.Amount)
.havingSumOf(Opportunity.Amount).greaterThan(100000)
.toAggregateList();
Decimal firstAccountTotal = rows[0].getDecimal('sum_Amount');isCached
global Boolean isCached()Indicates whether the last execution retrieved results from cache.
Returns Boolean — true if results came from cache
Example
QRY_Builder.Builder query = QRY_Builder.selectFrom(Account.SObjectType).withSystemMode().withSharing().withCache(300);
List<SObject> results = query.toList();
Boolean fromCache = query.isCached();logPerformanceIfSlowerThan
global QRY_Builder.Builder logPerformanceIfSlowerThan(Integer thresholdMs)Sets a custom performance threshold for this query. The query will be logged only if duration exceeds this threshold.
Parameters
| Parameter | Type | Description |
|---|---|---|
thresholdMs | Integer | Custom threshold in milliseconds |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.logPerformanceIfSlowerThan(500)
.toList();max
global QRY_Builder.Builder max(SObjectField field)Applies a MAX aggregate function.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to aggregate |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Opportunity.SObjectType)
.groupBy(Opportunity.StageName)
.max(Opportunity.Amount)
.toAggregateList();
Decimal firstStageLargest = rows[0].getDecimal('max_Amount');global virtual QRY_Builder.Builder max(SObjectField field, String alias)Applies a MAX aggregate under an explicit result alias. Aliased aggregates add up, so one query can combine several aggregates and read each back by its alias.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to take the maximum of |
alias | String | The result alias; must be a bare identifier, unique across the aliased selections |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if alias is not a bare identifier (a letter followed by letters, digits or underscores); or, when the query builds, if the alias duplicates an earlier aliased selection |
Example
.max(Opportunity.CreatedDate, 'lastSeen')min
global QRY_Builder.Builder min(SObjectField field)Applies a MIN aggregate function.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to aggregate |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Opportunity.SObjectType)
.groupBy(Opportunity.StageName)
.min(Opportunity.CloseDate)
.toAggregateList();
Date firstStageEarliestCloseDate = rows[0].getDate('min_CloseDate');global virtual QRY_Builder.Builder min(SObjectField field, String alias)Applies a MIN aggregate under an explicit result alias. Aliased aggregates add up, so one query can combine several aggregates and read each back by its alias.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to take the minimum of |
alias | String | The result alias; must be a bare identifier, unique across the aliased selections |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if alias is not a bare identifier (a letter followed by letters, digits or underscores); or, when the query builds, if the alias duplicates an earlier aliased selection |
Example
.min(Opportunity.CreatedDate, 'firstSeen')nullsFirst
global QRY_Builder.Builder nullsFirst()Sets the last ORDER BY clause to NULLS FIRST.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.orderBy(Account.Industry).ascending().nullsFirst()
.toList();nullsLast
global QRY_Builder.Builder nullsLast()Sets the last ORDER BY clause to NULLS LAST.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.orderBy(Account.Industry).ascending().nullsLast()
.toList();orCondition
global virtual QRY_Builder.ConditionBuilder orCondition(QRY_Function functionField)Starts an OR condition whose left-hand side is a SOQL function expression (for example a geolocation DISTANCE from QRY_Function.distanceInMiles). Mirrors orCondition(SObjectField) for function expressions.
Parameters
| Parameter | Type | Description |
|---|---|---|
functionField | QRY_Function | The function expression, from a QRY_Function factory |
Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator
Example
List<Account> nearby = QRY_Builder.selectFrom(Account.SObjectType)
.condition(QRY_Function.distanceInMiles(Account.BillingAddress, 37.775, -122.418)).lessThan(10)
.orCondition(QRY_Function.distanceInMiles(Account.ShippingAddress, 37.775, -122.418)).lessThan(10)
.toList();global QRY_Builder.ConditionBuilder orCondition(SObjectField field)Starts an OR condition on a field using an SObjectField token.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | Field token |
Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Industry).equals('Technology')
.orCondition(Account.Industry).equals('Finance')
.toList();global QRY_Builder.ConditionBuilder orCondition(String fieldName)Starts an OR condition on a field using its API name. The text may also be a date or distance function from QRY_Function, or toLabel around a field name. Text that comes from a page or a user must first be matched to a field through a list of fields you allow.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | A field API name, such as Name or Account.Owner.Name |
Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if the text is not blank and is not a field name |
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.condition('Industry').equals('Technology')
.orCondition('Industry').equals('Finance')
.toList();orderBy
global virtual QRY_Builder.Builder orderBy(QRY_Function functionField)Orders by a SOQL date-function expression, ascending (e.g. ORDER BY CALENDAR_MONTH(CloseDate)).
Parameters
| Parameter | Type | Description |
|---|---|---|
functionField | QRY_Function | The date-function expression, from a QRY_Function factory |
Returns QRY_Builder.Builder — Builder for chaining
Example
.orderBy(QRY_Function.calendarMonth(Opportunity.CloseDate))global virtual QRY_Builder.Builder orderBy(QRY_Function functionField, Boolean sortDescending)Orders by a SOQL date-function expression, ascending or descending.
Parameters
| Parameter | Type | Description |
|---|---|---|
functionField | QRY_Function | The date-function expression, from a QRY_Function factory |
sortDescending | Boolean | When true, sorts DESCENDING; otherwise ASCENDING |
Returns QRY_Builder.Builder — Builder for chaining
Example
.orderBy(QRY_Function.calendarMonth(Opportunity.CloseDate), true)global QRY_Builder.Builder orderBy(SObjectField field)Adds an ORDER BY clause (default ascending).
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | Field token to sort by |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.orderBy(Account.Name).ascending()
.toList();global QRY_Builder.Builder orderBy(SObjectField field, Boolean sortDescending)Adds an ORDER BY clause with a dynamic sort direction. Nulls placement defaults to standard SOQL behavior (NULLS FIRST for ASC, NULLS LAST for DESC).
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | Field token to sort by |
sortDescending | Boolean | When true, sorts DESCENDING; otherwise ASCENDING |
Returns QRY_Builder.Builder — Builder for chaining
Example
Boolean isDescending = true;
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.orderBy(Account.Name, isDescending)
.toList();global QRY_Builder.Builder orderBy(SObjectField field, Boolean sortDescending, Boolean nullsLast)Adds an ORDER BY clause with a dynamic sort direction and nulls placement.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | Field token to sort by |
sortDescending | Boolean | When true, sorts DESCENDING; otherwise ASCENDING |
nullsLast | Boolean | When true, places nulls last; otherwise places nulls first |
Returns QRY_Builder.Builder — Builder for chaining
Example
Boolean isDescending = true;
Boolean isNullsLast = true;
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.orderBy(Account.Name, isDescending, isNullsLast)
.toList();global QRY_Builder.Builder orderBy(String fieldName)Adds an ORDER BY clause (default ascending). The text is written as given. It may be one sort item or several joined by commas. A sort item is a field name or a date or distance function from QRY_Function, then ASC or DESC if wanted, then NULLS FIRST or NULLS LAST if wanted, such as Name DESC NULLS LAST, CreatedDate. Text that comes from a page or a user must first be matched to a field through a list of fields you allow.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | A field API name, such as Name or Account.Owner.Name, or a list of sort items |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if the text is not blank and is not a list of sort items |
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.orderBy('CreatedDate').descending()
.toList();global QRY_Builder.Builder orderBy(String fieldName, Boolean sortDescending)Adds an ORDER BY clause with a dynamic sort direction. Nulls placement defaults to standard SOQL behavior (NULLS FIRST for ASC, NULLS LAST for DESC). The text may be a list of sort items joined by commas, as for orderBy(String), but its last item must have no direction and no nulls order, because this method adds them. Text that comes from a page or a user must first be matched to a field through a list of fields you allow.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | A field API name, such as Name or Account.Owner.Name |
sortDescending | Boolean | When true, sorts DESCENDING; otherwise ASCENDING |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if the text is not blank and is not such a list |
Example
Boolean isDescending = false;
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.orderBy('CreatedDate', isDescending)
.toList();global QRY_Builder.Builder orderBy(String fieldName, Boolean sortDescending, Boolean nullsLast)Adds an ORDER BY clause with a dynamic sort direction and nulls placement. The text may be a list of sort items joined by commas, as for orderBy(String), but its last item must have no direction and no nulls order, because this method adds them. Text that comes from a page or a user must first be matched to a field through a list of fields you allow.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldName | String | A field API name, such as Name or Account.Owner.Name |
sortDescending | Boolean | When true, sorts DESCENDING; otherwise ASCENDING |
nullsLast | Boolean | When true, places nulls last; otherwise places nulls first |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if the text is not blank and is not such a list |
Example
Boolean isDescending = true;
Boolean isNullsLast = false;
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.orderBy('CreatedDate', isDescending, isNullsLast)
.toList();orderByCount
global virtual QRY_Builder.Builder orderByCount(SObjectField field, Boolean sortDescending)Orders an aggregate query by COUNT of a field (e.g. ORDER BY COUNT(Id) DESC), the SOQL form for ranking grouped rows by how many records each group holds. To read only the top groups, combine this with withLimit. No NULLS clause is added, because COUNT never returns null.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field whose COUNT orders the grouped rows |
sortDescending | Boolean | When true, sorts DESCENDING (largest groups first); otherwise ASCENDING |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if field is null |
Example
List<QRY_Builder.AggregateRow> topSources = QRY_Builder.selectFrom(Opportunity.SObjectType)
.groupBy(Opportunity.StageName)
.count(Opportunity.Id, 'rowTotal')
.orderByCount(Opportunity.Id, true)
.withLimit(3)
.toAggregateList();relatedField
global QRY_Builder.Builder relatedField(String parentField)Adds a single parent field. The text must be a field name or a path through parent records, such as Account.Owner.Name. Text that comes from a page or a user must first be matched to a field through a list of fields you allow.
Parameters
| Parameter | Type | Description |
|---|---|---|
parentField | String | A field API name, such as Name or Account.Owner.Name |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if the text is not blank and is not a field name or a path through parent records, such as Account.Owner.Name |
Example
List<Contact> contacts = QRY_Builder.selectFrom(Contact.SObjectType)
.relatedField('Account.Owner.Name')
.toList();relatedFields
global QRY_Builder.Builder relatedFields(List<String> parentFields)Adds parent (related) fields to the selection. Each text must be a field name or a path through parent records, such as Account.Owner.Name. Text that comes from a page or a user must first be matched to a field through a list of fields you allow.
Parameters
| Parameter | Type | Description |
|---|---|---|
parentFields | List | A list of field API names, such as Name or Account.Owner.Name |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if a text in the list is not blank and is not a field name or a path through parent records, such as Account.Owner.Name. Nothing is added then. |
Example
List<Contact> contacts = QRY_Builder.selectFrom(Contact.SObjectType)
.relatedFields(new List<String>{'Account.Name', 'Account.Industry'})
.toList();rollup
global QRY_Builder.Builder rollup()Flags the GROUP BY clause as ROLLUP for subtotals.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<QRY_Builder.AggregateRow> results = QRY_Builder.selectFrom(Opportunity.SObjectType)
.groupBy(Opportunity.StageName)
.groupBy(Opportunity.AccountId)
.sum(Opportunity.Amount)
.rollup()
.toAggregateList();selectAllFields
global QRY_Builder.Builder selectAllFields()Configures the query to select ALL fields on the object.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.selectAllFields()
.withLimit(10)
.toList();stripInaccessible
global QRY_Builder.Builder stripInaccessible()Strips inaccessible fields from results.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.stripInaccessible()
.toList();subselect
global QRY_Builder.Builder subselect(QRY_Builder.Builder childQuery, String relationshipName)Adds a child subquery (child relationship query). The relationship name is the API name of the child relationship, such as Contacts. It may have the parent object and a dot in front, such as Account.Contacts, as SOQL allows. Spaces around the name are removed. Text that comes from a page or a user must first be matched to a relationship through a list of names you allow.
Parameters
| Parameter | Type | Description |
|---|---|---|
childQuery | QRY_Builder.Builder | Configured Builder for the child object |
relationshipName | String | The child relationship API name (e.g., 'Contacts' or 'Account.Contacts') |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if the relationship name is not blank and is not one API name, or API names joined by dots, such as Contacts or Account.Contacts |
Example
QRY_Builder.Builder contactQuery = new QRY_Builder.Builder(Contact.SObjectType)
.fields(new List<SObjectField>{Contact.FirstName, Contact.LastName});
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.subselect(contactQuery, 'Contacts')
.toList();sum
global QRY_Builder.Builder sum(SObjectField field)Applies a SUM aggregate function.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to aggregate |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Opportunity.SObjectType)
.groupBy(Opportunity.StageName)
.sum(Opportunity.Amount)
.toAggregateList();
Decimal firstStageTotal = rows[0].getDecimal('sum_Amount');global virtual QRY_Builder.Builder sum(SObjectField field, String alias)Applies a SUM aggregate under an explicit result alias. Aliased aggregates add up, so one query can combine several aggregates and read each back by its alias.
Parameters
| Parameter | Type | Description |
|---|---|---|
field | SObjectField | The field to sum |
alias | String | The result alias; must be a bare identifier, unique across the aliased selections |
Returns QRY_Builder.Builder — Builder for chaining
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if alias is not a bare identifier (a letter followed by letters, digits or underscores); or, when the query builds, if the alias duplicates an earlier aliased selection |
Example
.sum(Opportunity.Amount, 'pipelineTotal')suppressPerformanceLogging
global QRY_Builder.Builder suppressPerformanceLogging()Stops this query from writing a performance log entry, even when it is slow. Use it for a query you expect to be slow, so it does not fill the logs. The last of suppressPerformanceLogging, forcePerformanceLogging and logPerformanceIfSlowerThan called on the builder is the one that applies.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.suppressPerformanceLogging()
.toList();toAggregateList
global List<QRY_Builder.AggregateRow> toAggregateList()Executes an aggregate query and returns results as typed AggregateRow wrappers. Use with aggregate methods like count(field, alias), sum(), avg(), min(), max() and groupBy(). The count() that ends a query and returns a number is not an aggregate read.
In a test, rows registered with TST_Mock.registerAggregateRows or QRY_Builder.setAggregateMock answer the query instead of the database.
Returns QRY_Builder.AggregateRow — List of AggregateRow wrappers
Throws
| Exception | Description |
|---|---|
| QueryException | With bypassSharing() alone, under user mode, when the running user cannot read the object, or the object of a query inside isIn(), notIn() or subselect(). |
| UTIL_Exceptions.IllegalStateException | In a test, when record mocks are registered for the object type but no aggregate rows are. Record mocks never answer an aggregate query. Also with bypassSharing() alone, under user mode: totals and group values cannot have the fields the running user cannot read removed. Add withSystemMode(). |
Example
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Account.SObjectType)
.count(Account.Id, 'total')
.groupBy(Account.Industry)
.toAggregateList();
Map<String, Integer> totalByIndustry = new Map<String, Integer>();
for(QRY_Builder.AggregateRow row : rows)
{
totalByIndustry.put(row.getString('Industry'), row.getInteger('total'));
}toCursor
global Database.Cursor toCursor()Returns a Database.Cursor for reading a large set of records in parts. The cursor is opened with the sharing this builder was set up with, or with the caller's own sharing when none is set. So a cursor built with withSystemMode() and bypassSharing() fetches every row the query matches, whatever the record sharing, on every later fetch in this transaction or a later one. An exception registered through TST_Mock.throwsException() is thrown from this call exactly as it is from every other method that runs the query.
Returns Database.Cursor — Database.Cursor
Throws
| Exception | Description |
|---|---|
| QueryException | With bypassSharing() alone, under user mode, when the running user cannot read the object, or the object of a query inside isIn(), notIn() or subselect(). |
| UTIL_Exceptions.IllegalStateException | With bypassSharing() alone, under user mode. The rows are fetched later, so the fields the running user cannot read cannot be removed. Add withSystemMode(). |
Example
Database.Cursor cursor = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Type).equals('Customer')
.toCursor();toList
global List<SObject> toList()Executes the query and returns a List of SObjects.
Returns SObject — List results
Throws
| Exception | Description |
|---|---|
| QueryException | With bypassSharing() alone, under user mode, when the running user cannot read the object, the object of a query inside isIn(), notIn() or subselect(), or a parent object on a selected path. |
| UTIL_Exceptions.IllegalStateException | In a test, when the query is an aggregate query and rows registered with TST_Mock.registerAggregateRows answer it. Read an aggregate query with toAggregateList(). The other methods that return records, such as getFirst(), getPage() and asMap(), throw in the same case. |
| UTIL_Exceptions.IllegalStateException | With bypassSharing() alone, under user mode, when the query is an aggregate query, when it filters or sorts on a field the running user cannot read, when it selects a path or adds a child query through a lookup the running user cannot read, or when it selects text the builder cannot check, such as a child query written as text. Add withSystemMode(). getFirst() and the as methods, such as asMap(), throw in the same cases. |
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Industry).equals('Technology')
.toList();toQueryLocator
global Database.QueryLocator toQueryLocator()Returns a Database.QueryLocator for batch processing.
Returns Database.QueryLocator — Database.QueryLocator
Throws
| Exception | Description |
|---|---|
| QueryException | With bypassSharing() alone, under user mode, when the running user cannot read the object, or the object of a query inside isIn(), notIn() or subselect(). |
| UTIL_Exceptions.IllegalStateException | With bypassSharing() alone, under user mode. A batch job reads the rows later, so the fields the running user cannot read cannot be removed. Add withSystemMode(). |
Example
Database.QueryLocator locator = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Type).equals('Customer')
.toQueryLocator();toSoql
global String toSoql()Generates and returns the SOQL string without executing it.
Returns String — The built SOQL query string
Example
String soql = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Industry).equals('Technology')
.toSoql();usingScope
global QRY_Builder.Builder usingScope(QRY_Builder.Scope scopeValue)Filters records by visibility scope using USING SCOPE clause.
Parameters
| Parameter | Type | Description |
|---|---|---|
scopeValue | QRY_Builder.Scope | The scope to apply |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.usingScope(QRY_Builder.Scope.MINE)
.toList();withCache
global QRY_Builder.Builder withCache(Integer ttlSeconds)Enables caching for this query. A non-null time-to-live means withCache(UTIL_Cache.Scope.AUTO, ttlSeconds); a null one requests no caching. A user-mode read is kept in memory for this transaction. A system-mode read that leaves the sharing setting to the calling class is not cached, because the cache cannot tell one calling class's sharing from another's; to cache a system-mode read, state the setting with withSharing() or bypassSharing(). A read with bypassSharing() alone under user mode is cached as a system-mode read, and the fields each running user cannot read are removed from the rows when they are returned.
Parameters
| Parameter | Type | Description |
|---|---|---|
ttlSeconds | Integer | Time-to-live in seconds for Platform Cache; ignored in memory; null requests no caching |
Returns QRY_Builder.Builder — Builder for chaining
Example
Account account = (Account)QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Id).equals(accountId)
.withSystemMode()
.withSharing()
.withCache(300)
.getFirst();global virtual QRY_Builder.Builder withCache(UTIL_Cache.Scope scope, Integer ttlSeconds)Caches this query's results in the given scope. AUTO is not a place: it asks for the most durable storage that is safe for this read when it runs, Platform Cache for a system-mode read where a partition keeps it, and memory for this transaction otherwise. A user-mode read is only ever kept in memory for this transaction. A system-mode read whose sharing is left to the calling class is not cached; state it with withSharing() or bypassSharing(). A read with bypassSharing() alone under user mode is cached as a system-mode read, and the fields each running user cannot read are removed from the rows when they are returned. The last caching call on a builder wins.
Parameters
| Parameter | Type | Description |
|---|---|---|
scope | UTIL_Cache.Scope | Where results may be kept; null means no caching |
ttlSeconds | Integer | Time-to-live in seconds for Platform Cache; ignored in memory; null uses the default |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> parents = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Id).isIn(parentIds)
.withCache(UTIL_Cache.Scope.IN_TRANSACTION, null)
.toList();withDataCategory
global QRY_Builder.DataCategoryBuilder withDataCategory(String groupName)Starts a WITH DATA CATEGORY filter for the specified data category group. Text that comes from a page or a user must first be matched to a group through a list of names you allow.
Parameters
| Parameter | Type | Description |
|---|---|---|
groupName | String | The data category group API name, such as Geography__c |
Returns QRY_Builder.DataCategoryBuilder — DataCategoryBuilder for operator selection
Throws
| Exception | Description |
|---|---|
| IllegalArgumentException | if groupName is blank, or is not a single API name, such as Name |
Example
List<SObject> articles = QRY_Builder.selectFrom(KnowledgeArticleVersion.SObjectType)
.fields(new List<String>{'Id', 'Title'})
.condition('PublishStatus').equals('Online')
.withDataCategory('Geography__c').at('USA__c')
.withDataCategory('Product__c').below('Electronics__c')
.toList();withLimit
global QRY_Builder.Builder withLimit(Integer recordLimit)Sets the maximum number of records to return (LIMIT).
Parameters
| Parameter | Type | Description |
|---|---|---|
recordLimit | Integer | Maximum number of records |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.withLimit(100)
.toList();withOffset
global QRY_Builder.Builder withOffset(Integer rowNumber)Sets the record offset (OFFSET).
Parameters
| Parameter | Type | Description |
|---|---|---|
rowNumber | Integer | Number of records to skip |
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.withLimit(25)
.withOffset(50)
.toList();withoutCache
global virtual QRY_Builder.Builder withoutCache()Makes this query read from the database, whatever caching the selector or an earlier call asked for. The last caching call on a builder wins.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> fresh = new SEL_Account().query.withoutCache().condition(Account.Id).isIn(ids).toList();withoutSecurity
global QRY_Builder.Builder withoutSecurity()Turns off every security check the builder controls, in one call. The query runs in SYSTEM_MODE, so object and field permissions are not checked. The stripInaccessible() choice is cleared. And record sharing is ignored through the without sharing proxy, exactly as withSystemMode() followed by bypassSharing() would do. Both bypasses are recorded in the bypass audit. To skip object and field permissions but keep the record sharing of the calling class, use withSystemMode() instead. This method ignores the UserModeQueries_Enabled flag.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.withoutSecurity()
.toList();withSharing
global QRY_Builder.Builder withSharing()Enforces sharing rules using a with sharing proxy class.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.withSharing()
.toList();withSystemMode
global QRY_Builder.Builder withSystemMode()Runs the query in SYSTEM_MODE, whatever the UserModeQueries_Enabled feature flag says. Use it for a query that must read custom metadata, system tables, or objects the running user is not meant to have object or field access (CRUD/FLS) to. Each call is recorded in the bypass audit when the query runs.
Returns QRY_Builder.Builder — Builder for chaining
Example
TriggerSetting__mdt setting = (TriggerSetting__mdt)QRY_Builder.selectFrom(TriggerSetting__mdt.SObjectType)
.withSystemMode()
.condition(TriggerSetting__mdt.SObjectType__c).equals('Account')
.getFirst();withUserMode
global QRY_Builder.Builder withUserMode()Runs the query in USER_MODE. With bypassSharing(), the read runs without record sharing but still checks object and field permissions.
Returns QRY_Builder.Builder — Builder for chaining
Example
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.withUserMode()
.toList();Constructors
| Constructor | Description |
|---|---|
| global Builder() | Creates a builder with no object to read: objectType stays null, and nothing can set it later. |
| global Builder(SObjectType sObjectType) | Creates a builder that reads the given object. |
Builder()
global Builder()Creates a builder with no object to read: objectType stays null, and nothing can set it later. To build a query you will run, use QRY_Builder.selectFrom or the constructor that takes an SObjectType.
Example
QRY_Builder.Builder query = new QRY_Builder.Builder();Builder(SObjectType sObjectType)
global Builder(SObjectType sObjectType)Creates a builder that reads the given object. QRY_Builder.selectFrom calls this constructor, so the two give the same builder. A class that extends Builder calls it to set the object it reads.
Parameters
| Parameter | Type | Description |
|---|---|---|
sObjectType | SObjectType | The SObject to query |
Example
QRY_Builder.Builder query = new QRY_Builder.Builder(Account.SObjectType);Properties
| Property | Description |
|---|---|
| global SObjectType objectType | The object this builder reads, as passed to QRY_Builder.selectFrom. |
objectType
global SObjectType objectTypeType: SObjectType
The object this builder reads, as passed to QRY_Builder.selectFrom. You can read it but not change it. It is null on a builder made with the constructor that takes no arguments.