Skip to content

QRY_Builder.Builder ​

Class · Group: Query Infrastructure

Learn it: Fast Start - Selectors and Selectors guide

apex
global virtual inherited sharing class QRY_Builder.Builder implements IF_Queryable

Implements: 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

apex
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.

GroupMethodsWorked example
Choose fieldsaddField addFields addFieldSet fields fieldSet getDefaultFields relatedField relatedFields selectAllFields subselectSELECT and FROM
Filter recordsaddCondition allRows andCondition condition orCondition usingScope withDataCategoryWHERE Conditions
Sort and limitascending descending nullsFirst nullsLast orderBy withLimit withOffsetORDER BY and LIMIT
Count and totalavg count countDistinct cube groupBy grouping havingAvgOf havingCount havingCountOf havingMaxOf havingMinOf havingSumOf max min orderByCount rollup sumAggregate Functions
Run the queryasGroupedMapById asGroupedMapByString asIdList asIdSet asMap asMapById asMapByString asStringSet asValueSet exists getFirst getFirstAggregate getPage getRandomItem getRandomItems toAggregateList toCursor toList toQueryLocatorResult Transformation
Security and row lockingbypassSharing forReference forUpdate forView stripInaccessible withoutSecurity withSharing withSystemMode withUserModeSecurity & Row Locking
OtherforcePerformanceLogging isCached logPerformanceIfSlowerThan suppressPerformanceLogging toSoql withCache withoutCacheCaching Queries, Query Performance Logging

Methods ​

MethodDescription
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 ​

apex
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

ParameterTypeDescription
conditionQRY_Condition.EvaluableThe condition to add (created via QRY_Condition classes)

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
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 ​

apex
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

ParameterTypeDescription
functionFieldQRY_FunctionThe date-function expression, from a QRY_Function factory
aliasStringThe read-back alias for the projected expression; must be a bare identifier

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif alias is not a bare identifier (a letter followed by letters, digits or underscores)

Example

apex
QRY_Builder.selectFrom(Opportunity.SObjectType)
    .addField(QRY_Function.calendarMonth(Opportunity.CloseDate), 'closeMonth')
    .count('Id')
    .groupBy(QRY_Function.calendarMonth(Opportunity.CloseDate))
    .toAggregateList();
apex
global QRY_Builder.Builder addField(SObjectField objectField)

Adds a single field without disabling default fields.

Parameters

ParameterTypeDescription
objectFieldSObjectFieldSObjectField token

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .addField(Account.Website)
    .toList();
apex
global QRY_Builder.Builder addField(String fieldName)

Adds a single field without disabling default fields.

Parameters

ParameterTypeDescription
fieldNameStringAPI name

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .addField('Website')
    .toList();

addFields ​

apex
global QRY_Builder.Builder addFields(List<SObjectField> objectFields)

Adds fields to the selection without disabling default fields.

Parameters

ParameterTypeDescription
objectFieldsListList of SObjectField tokens

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .addFields(new List<SObjectField>{Account.Phone, Account.Website})
    .toList();
apex
global QRY_Builder.Builder addFields(List<String> fieldNames)

Adds fields to the selection without disabling default fields.

Parameters

ParameterTypeDescription
fieldNamesListList of field API names

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .addFields(new List<String>{'Phone', 'Website'})
    .toList();

addFieldSet ​

apex
global QRY_Builder.Builder addFieldSet(FieldSet aFieldset)

Adds fields from a FieldSet token without disabling default fields.

Parameters

ParameterTypeDescription
aFieldsetFieldSetThe Schema.FieldSet token

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
FieldSet fs = SObjectType.Account.fieldSets.Account_Summary;
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .addFieldSet(fs)
    .toList();
apex
global QRY_Builder.Builder addFieldSet(String fieldSetName)

Adds fields from a FieldSet without disabling default fields.

Parameters

ParameterTypeDescription
fieldSetNameStringThe API Name of the FieldSet

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .addFieldSet('Account_Summary')
    .toList();

allRows ​

apex
global QRY_Builder.Builder allRows()

Includes deleted and archived records (ALL ROWS).

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.IsDeleted).equals(true)
    .allRows()
    .toList();

andCondition ​

apex
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

ParameterTypeDescription
functionFieldQRY_FunctionThe function expression, from a QRY_Function factory

Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator

Example

apex
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();
apex
global QRY_Builder.ConditionBuilder andCondition(SObjectField field)

Starts an AND condition on a field using an SObjectField token.

Parameters

ParameterTypeDescription
fieldSObjectFieldField token

Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Industry).equals('Technology')
    .andCondition(Account.Type).equals('Customer')
    .toList();
apex
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

ParameterTypeDescription
fieldNameStringA field API name, such as Name or Account.Owner.Name

Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator

Throws

ExceptionDescription
IllegalArgumentExceptionif the text is not blank and is not a field name

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .condition('Industry').equals('Technology')
    .andCondition('Type').equals('Customer')
    .toList();

ascending ​

apex
global QRY_Builder.Builder ascending()

Sets the last ORDER BY clause to ASCENDING.

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .orderBy(Account.Name).ascending()
    .toList();

asGroupedMapById ​

apex
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

ParameterTypeDescription
keyFieldSObjectFieldThe 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

apex
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);
apex
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

ParameterTypeDescription
fieldNameStringThe 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

apex
Map<Id, List<SObject>> contactsByOwner = QRY_Builder.selectFrom(Contact.SObjectType)
    .addField(Contact.OwnerId)
    .asGroupedMapById('OwnerId');

asGroupedMapByString ​

apex
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

ParameterTypeDescription
keyFieldSObjectFieldThe 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

apex
Map<String, List<SObject>> accountsByIndustry = QRY_Builder.selectFrom(Account.SObjectType)
    .addField(Account.Industry)
    .asGroupedMapByString(Account.Industry);
apex
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

ParameterTypeDescription
fieldNameStringThe 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

apex
Map<String, List<SObject>> accountsByOwnerName = QRY_Builder.selectFrom(Account.SObjectType)
    .addField(Account.OwnerId)
    .relatedField('Owner.Name')
    .asGroupedMapByString('Owner.Name');

asIdList ​

apex
global List<Id> asIdList()

Returns the results as a List of Ids.

Returns Id — List

Example

apex
List<Id> accountIds = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Type).equals('Customer')
    .asIdList();

asIdSet ​

apex
global Set<Id> asIdSet()

Executes the query and returns a Set of record Ids.

Returns Id — Set

Example

apex
Set<Id> accountIds = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Type).equals('Customer')
    .asIdSet();

asMap ​

apex
global Map<Id, SObject> asMap()

Executes the query and returns results as a Map .

Returns SObject — Map

Example

apex
Map<Id, SObject> accountMap = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Type).equals('Customer')
    .asMap();

asMapById ​

apex
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

ParameterTypeDescription
keyFieldSObjectFieldThe 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

apex
Map<Id, SObject> contactsByAccount = QRY_Builder.selectFrom(Contact.SObjectType)
    .addFields(new List<SObjectField>{Contact.Id, Contact.AccountId})
    .condition(Contact.AccountId).isNotNull()
    .asMapById(Contact.AccountId);
apex
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

ParameterTypeDescription
fieldNameStringThe 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

apex
Map<Id, SObject> contactsByOwner = QRY_Builder.selectFrom(Contact.SObjectType)
    .addField(Contact.OwnerId)
    .asMapById('OwnerId');

asMapByString ​

apex
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

ParameterTypeDescription
keyFieldSObjectFieldThe 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

apex
Map<String, SObject> accountByName = QRY_Builder.selectFrom(Account.SObjectType)
    .addField(Account.Name)
    .asMapByString(Account.Name);
apex
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

ParameterTypeDescription
fieldNameStringThe 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

apex
Map<String, SObject> accountByOwnerName = QRY_Builder.selectFrom(Account.SObjectType)
    .addField(Account.OwnerId)
    .relatedField('Owner.Name')
    .asMapByString('Owner.Name');

asStringSet ​

apex
global Set<String> asStringSet(SObjectField field)

Executes the query and returns a Set of distinct String values for the specified field.

Parameters

ParameterTypeDescription
fieldSObjectFieldThe field token to extract String values from

Returns String — Set of String field values (nulls excluded)

Example

apex
Set<String> nicknames = QRY_Builder.selectFrom(User.SObjectType)
    .addField(User.CommunityNickname)
    .condition(User.CommunityNickname).startsWith('Billy')
    .asStringSet(User.CommunityNickname);
apex
global Set<String> asStringSet(String fieldName)

Executes the query and returns a Set of distinct String values for the specified field.

Parameters

ParameterTypeDescription
fieldNameStringThe field API name to extract String values from

Returns String — Set of String field values (nulls excluded)

Example

apex
Set<String> ownerNames = QRY_Builder.selectFrom(Account.SObjectType)
    .relatedField('Owner.Name')
    .asStringSet('Owner.Name');

asValueSet ​

apex
global Set<Object> asValueSet(SObjectField field)

Executes the query and returns a Set of distinct values for the specified field.

Parameters

ParameterTypeDescription
fieldSObjectFieldThe field token to extract values from

Returns Object — Set of field values

Example

apex
Set<Object> industries = QRY_Builder.selectFrom(Account.SObjectType)
    .addField(Account.Industry)
    .asValueSet(Account.Industry);
apex
global Set<Object> asValueSet(String fieldName)

Executes the query and returns a Set of distinct values for the specified field.

Parameters

ParameterTypeDescription
fieldNameStringThe field API name to extract values from

Returns Object — Set of field values

Example

apex
Set<Object> ownerNames = QRY_Builder.selectFrom(Account.SObjectType)
    .relatedField('Owner.Name')
    .asValueSet('Owner.Name');

avg ​

apex
global QRY_Builder.Builder avg(SObjectField field)

Applies an AVG aggregate function.

Parameters

ParameterTypeDescription
fieldSObjectFieldThe field to aggregate

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Opportunity.SObjectType)
    .groupBy(Opportunity.StageName)
    .avg(Opportunity.Amount)
    .toAggregateList();
Decimal firstStageAverage = rows[0].getDecimal('avg_Amount');
apex
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

ParameterTypeDescription
fieldSObjectFieldThe field to average
aliasStringThe result alias; must be a bare identifier, unique across the aliased selections

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif 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

apex
.avg(Opportunity.Amount, 'meanAmount')

bypassSharing ​

apex
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() or DISTANCE(), written as text or from QRY_Function), and a path through parent records such as Parent__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, Who or Owner, 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 as WhatId, and the field of the Name record, such as Name in What.Name. The objects the lookup points to are not checked;

  • for some users Salesforce hides the ProfileId, UserRoleId and RecordTypeId fields of the Name record, so a filter on What.ProfileId or on What.RecordType.Name is refused for them;

  • because the read ignores sharing, a filter on What.Name covers 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.Name without read on WhatId, Account.Name on a contact without read on Account, child queries, and TYPEOF, whose relationship and each object after WHEN must 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 Phone in Account.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 each TYPEOF as 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 WhatId for the Events of an account, as user mode refuses it, even when the child query selects only Id. 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 in Account.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

apex
// 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();
apex
// 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 ​

apex
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

ParameterTypeDescription
functionFieldQRY_FunctionThe function expression, from a QRY_Function factory

Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator

Example

apex
List<Account> nearby = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(QRY_Function.distanceInMiles(Account.BillingAddress, 37.775, -122.418)).lessThan(10)
    .toList();
apex
global QRY_Builder.ConditionBuilder condition(SObjectField objectField)

Starts a WHERE condition on a field using an SObjectField token.

Parameters

ParameterTypeDescription
objectFieldSObjectFieldField token

Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Industry).equals('Technology')
    .toList();
apex
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

ParameterTypeDescription
fieldNameStringA field API name, such as Name or Account.Owner.Name

Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator

Throws

ExceptionDescription
IllegalArgumentExceptionif the text is not blank and is not a field name

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .condition('Industry').equals('Technology')
    .toList();

count ​

apex
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

ExceptionDescription
QueryExceptionWith 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.IllegalStateExceptionWith 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

apex
Integer total = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Type).equals('Customer')
    .count();
apex
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

ParameterTypeDescription
fieldSObjectFieldThe field to count
aliasStringThe result alias; must be a bare identifier, unique across the aliased selections

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif 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

apex
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Opportunity.SObjectType)
    .groupBy(Opportunity.StageName)
    .count(Opportunity.Id, 'rowTotal')
    .min(Opportunity.CreatedDate, 'firstSeen')
    .toAggregateList();
apex
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

ParameterTypeDescription
fieldNameStringA field API name, such as Name or Account.Owner.Name (or null for COUNT())

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif the text is not blank and is not a field name or a path through parent records, such as Account.Owner.Name

Example

apex
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Account.SObjectType)
    .groupBy(Account.Industry)
    .count('Id')
    .toAggregateList();
Integer firstIndustryCount = rows[0].getInteger('count_Id');

countDistinct ​

apex
global QRY_Builder.Builder countDistinct(SObjectField field)

Applies a COUNT_DISTINCT aggregate function.

Parameters

ParameterTypeDescription
fieldSObjectFieldThe field to count distinct values

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
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');
apex
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

ParameterTypeDescription
fieldSObjectFieldThe field to count distinct values of
aliasStringThe result alias; must be a bare identifier, unique across the aliased selections

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif 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

apex
.countDistinct(Contact.Email, 'uniqueEmails')
apex
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

ParameterTypeDescription
fieldNameStringA field API name, such as Name or Account.Owner.Name

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif the text is not blank and is not a field name or a path through parent records, such as Account.Owner.Name

Example

apex
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 ​

apex
global QRY_Builder.Builder cube()

Flags the GROUP BY clause as CUBE for cross-tabulation.

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<QRY_Builder.AggregateRow> results = QRY_Builder.selectFrom(Opportunity.SObjectType)
    .groupBy(Opportunity.StageName)
    .groupBy(Opportunity.LeadSource)
    .sum(Opportunity.Amount)
    .cube()
    .toAggregateList();

descending ​

apex
global QRY_Builder.Builder descending()

Sets the last ORDER BY clause to DESCENDING.

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .orderBy(Account.CreatedDate).descending()
    .toList();

exists ​

apex
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

ExceptionDescription
QueryExceptionWith 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.IllegalStateExceptionWith 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

apex
Boolean hasCustomers = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Type).equals('Customer')
    .exists();

fields ​

apex
global QRY_Builder.Builder fields(List<SObjectField> objectFields)

Explicitly select fields using SObjectField tokens.

Parameters

ParameterTypeDescription
objectFieldsListList of SObjectField tokens

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .fields(new List<SObjectField>{Account.Name, Account.Industry})
    .toList();
apex
global QRY_Builder.Builder fields(List<String> fieldNames)

Explicitly select fields by API name.

Parameters

ParameterTypeDescription
fieldNamesListList of field API names

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .fields(new List<String>{'Name', 'Industry', 'AnnualRevenue'})
    .toList();

fieldSet ​

apex
global QRY_Builder.Builder fieldSet(FieldSet aFieldset)

Selects fields from a FieldSet token.

Parameters

ParameterTypeDescription
aFieldsetFieldSetThe Schema.FieldSet token

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
FieldSet fs = SObjectType.Account.fieldSets.Account_Summary;
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .fieldSet(fs)
    .toList();
apex
global QRY_Builder.Builder fieldSet(String fieldSetName)

Selects fields from a FieldSet.

Parameters

ParameterTypeDescription
fieldSetNameStringThe API Name of the FieldSet

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .fieldSet('Account_Summary')
    .toList();

forcePerformanceLogging ​

apex
global QRY_Builder.Builder forcePerformanceLogging()

Forces performance logging regardless of threshold for this query.

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .forcePerformanceLogging()
    .toList();

forReference ​

apex
global QRY_Builder.Builder forReference()

Locks returned records FOR REFERENCE.

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Id).equals(accountId)
    .forReference()
    .toList();

forUpdate ​

apex
global QRY_Builder.Builder forUpdate()

Locks returned records FOR UPDATE.

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Id).equals(accountId)
    .forUpdate()
    .toList();

forView ​

apex
global QRY_Builder.Builder forView()

Locks returned records FOR VIEW.

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Id).equals(accountId)
    .forView()
    .toList();

getDefaultFields ​

apex
global virtual Set<String> getDefaultFields()

Override to provide default fields for this selector.

Returns String — Set of field API names

Example

apex
public override Set<String> getDefaultFields()
{
    return new Set<String>{'Name', 'Industry', 'Type'};
}

getFirst ​

apex
global SObject getFirst()

Executes the query and returns the first record (or null).

Returns SObject — Single SObject or null

Example

apex
Account account = (Account)QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Id).equals(accountId)
    .getFirst();

getFirstAggregate ​

apex
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

ExceptionDescription
QueryExceptionWith 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.IllegalStateExceptionWith bypassSharing() alone, under user mode: totals and group values cannot have the fields the running user cannot read removed. Add withSystemMode().

Example

apex
QRY_Builder.AggregateRow row = QRY_Builder.selectFrom(Opportunity.SObjectType)
    .sum(Opportunity.Amount, 'totalAmount')
    .getFirstAggregate();
Decimal totalAmount = row.getDecimal('totalAmount');

getPage ​

apex
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

ParameterTypeDescription
requestedPageNumberIntegerThe page number to retrieve (1-based)
requestedPageSizeIntegerNumber of records per page, from 1 to 2000

Returns QRY_Builder.QueryPage — Page containing records and pagination metadata

Throws

ExceptionDescription
IllegalArgumentExceptionWhen the page number is below 1, or the page size is outside 1 to 2000
QueryExceptionWith 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.IllegalStateExceptionWhen 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

apex
QRY_Builder.QueryPage page = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Type).equals('Customer')
    .orderBy(Account.Name).ascending()
    .getPage(2, 25);

getRandomItem ​

apex
global SObject getRandomItem()

Returns a single random record matching the query criteria.

Returns SObject — Single random SObject or null

Example

apex
Account random = (Account)QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Type).equals('Customer')
    .getRandomItem();

getRandomItems ​

apex
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

ParameterTypeDescription
randomCountIntegerMaximum number of random records to return

Returns SObject — List of random SObjects

Throws

ExceptionDescription
QueryExceptionWith 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.IllegalStateExceptionIn 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

apex
List<Account> randoms = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Type).equals('Customer')
    .getRandomItems(5);

groupBy ​

apex
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

ParameterTypeDescription
functionFieldQRY_FunctionThe date-function expression, from a QRY_Function factory

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
QRY_Builder.selectFrom(Opportunity.SObjectType)
    .addField(QRY_Function.calendarMonth(Opportunity.CloseDate), 'closeMonth')
    .count('Id')
    .groupBy(QRY_Function.calendarMonth(Opportunity.CloseDate))
    .toAggregateList();
apex
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

ParameterTypeDescription
groupFieldSObjectFieldThe field to group by

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<QRY_Builder.AggregateRow> results = QRY_Builder.selectFrom(Account.SObjectType)
    .groupBy(Account.Industry)
    .groupBy(Account.Rating)
    .count('Id')
    .toAggregateList();
apex
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

ParameterTypeDescription
groupFieldStringA 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

ExceptionDescription
IllegalArgumentExceptionif the text is not blank and is not a list of field names or date functions

Example

apex
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Account.SObjectType)
    .groupBy('Industry')
    .count('Id')
    .toAggregateList();
Integer firstIndustryCount = rows[0].getInteger('count_Id');

grouping ​

apex
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

ParameterTypeDescription
fieldSObjectFieldThe field to wrap in GROUPING()

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<QRY_Builder.AggregateRow> results = QRY_Builder.selectFrom(Opportunity.SObjectType)
    .groupBy(Opportunity.StageName)
    .grouping(Opportunity.StageName)
    .sum(Opportunity.Amount)
    .rollup()
    .toAggregateList();
apex
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

ParameterTypeDescription
fieldNameStringA 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

ExceptionDescription
IllegalArgumentExceptionif the text is not blank and is not a field name or a date function

Example

apex
.groupBy('Industry').grouping('Industry').rollup()

havingAvgOf ​

apex
global QRY_Builder.ConditionBuilder havingAvgOf(SObjectField field)

Starts a HAVING condition on the AVG of a field.

Parameters

ParameterTypeDescription
fieldSObjectFieldThe field to aggregate

Returns QRY_Builder.ConditionBuilder — ConditionBuilder configured for HAVING

Example

apex
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 ​

apex
global QRY_Builder.ConditionBuilder havingCount()

Starts a HAVING condition on the global COUNT().

Returns QRY_Builder.ConditionBuilder — ConditionBuilder configured for HAVING

Example

apex
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 ​

apex
global QRY_Builder.ConditionBuilder havingCountOf(SObjectField field)

Starts a HAVING condition on the COUNT of a field.

Parameters

ParameterTypeDescription
fieldSObjectFieldThe field to count

Returns QRY_Builder.ConditionBuilder — ConditionBuilder configured for HAVING

Example

apex
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 ​

apex
global QRY_Builder.ConditionBuilder havingMaxOf(SObjectField field)

Starts a HAVING condition on the MAX of a field.

Parameters

ParameterTypeDescription
fieldSObjectFieldThe field to aggregate

Returns QRY_Builder.ConditionBuilder — ConditionBuilder configured for HAVING

Example

apex
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 ​

apex
global QRY_Builder.ConditionBuilder havingMinOf(SObjectField field)

Starts a HAVING condition on the MIN of a field.

Parameters

ParameterTypeDescription
fieldSObjectFieldThe field to aggregate

Returns QRY_Builder.ConditionBuilder — ConditionBuilder configured for HAVING

Example

apex
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 ​

apex
global QRY_Builder.ConditionBuilder havingSumOf(SObjectField field)

Starts a HAVING condition on the SUM of a field.

Parameters

ParameterTypeDescription
fieldSObjectFieldThe field to aggregate

Returns QRY_Builder.ConditionBuilder — ConditionBuilder configured for HAVING

Example

apex
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 ​

apex
global Boolean isCached()

Indicates whether the last execution retrieved results from cache.

Returns Boolean — true if results came from cache

Example

apex
QRY_Builder.Builder query = QRY_Builder.selectFrom(Account.SObjectType).withSystemMode().withSharing().withCache(300);
List<SObject> results = query.toList();
Boolean fromCache = query.isCached();

logPerformanceIfSlowerThan ​

apex
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

ParameterTypeDescription
thresholdMsIntegerCustom threshold in milliseconds

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .logPerformanceIfSlowerThan(500)
    .toList();

max ​

apex
global QRY_Builder.Builder max(SObjectField field)

Applies a MAX aggregate function.

Parameters

ParameterTypeDescription
fieldSObjectFieldThe field to aggregate

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Opportunity.SObjectType)
    .groupBy(Opportunity.StageName)
    .max(Opportunity.Amount)
    .toAggregateList();
Decimal firstStageLargest = rows[0].getDecimal('max_Amount');
apex
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

ParameterTypeDescription
fieldSObjectFieldThe field to take the maximum of
aliasStringThe result alias; must be a bare identifier, unique across the aliased selections

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif 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

apex
.max(Opportunity.CreatedDate, 'lastSeen')

min ​

apex
global QRY_Builder.Builder min(SObjectField field)

Applies a MIN aggregate function.

Parameters

ParameterTypeDescription
fieldSObjectFieldThe field to aggregate

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Opportunity.SObjectType)
    .groupBy(Opportunity.StageName)
    .min(Opportunity.CloseDate)
    .toAggregateList();
Date firstStageEarliestCloseDate = rows[0].getDate('min_CloseDate');
apex
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

ParameterTypeDescription
fieldSObjectFieldThe field to take the minimum of
aliasStringThe result alias; must be a bare identifier, unique across the aliased selections

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif 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

apex
.min(Opportunity.CreatedDate, 'firstSeen')

nullsFirst ​

apex
global QRY_Builder.Builder nullsFirst()

Sets the last ORDER BY clause to NULLS FIRST.

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .orderBy(Account.Industry).ascending().nullsFirst()
    .toList();

nullsLast ​

apex
global QRY_Builder.Builder nullsLast()

Sets the last ORDER BY clause to NULLS LAST.

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .orderBy(Account.Industry).ascending().nullsLast()
    .toList();

orCondition ​

apex
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

ParameterTypeDescription
functionFieldQRY_FunctionThe function expression, from a QRY_Function factory

Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator

Example

apex
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();
apex
global QRY_Builder.ConditionBuilder orCondition(SObjectField field)

Starts an OR condition on a field using an SObjectField token.

Parameters

ParameterTypeDescription
fieldSObjectFieldField token

Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Industry).equals('Technology')
    .orCondition(Account.Industry).equals('Finance')
    .toList();
apex
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

ParameterTypeDescription
fieldNameStringA field API name, such as Name or Account.Owner.Name

Returns QRY_Builder.ConditionBuilder — ConditionBuilder for specifying the operator

Throws

ExceptionDescription
IllegalArgumentExceptionif the text is not blank and is not a field name

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .condition('Industry').equals('Technology')
    .orCondition('Industry').equals('Finance')
    .toList();

orderBy ​

apex
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

ParameterTypeDescription
functionFieldQRY_FunctionThe date-function expression, from a QRY_Function factory

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
.orderBy(QRY_Function.calendarMonth(Opportunity.CloseDate))
apex
global virtual QRY_Builder.Builder orderBy(QRY_Function functionField, Boolean sortDescending)

Orders by a SOQL date-function expression, ascending or descending.

Parameters

ParameterTypeDescription
functionFieldQRY_FunctionThe date-function expression, from a QRY_Function factory
sortDescendingBooleanWhen true, sorts DESCENDING; otherwise ASCENDING

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
.orderBy(QRY_Function.calendarMonth(Opportunity.CloseDate), true)
apex
global QRY_Builder.Builder orderBy(SObjectField field)

Adds an ORDER BY clause (default ascending).

Parameters

ParameterTypeDescription
fieldSObjectFieldField token to sort by

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .orderBy(Account.Name).ascending()
    .toList();
apex
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

ParameterTypeDescription
fieldSObjectFieldField token to sort by
sortDescendingBooleanWhen true, sorts DESCENDING; otherwise ASCENDING

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
Boolean isDescending = true;
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .orderBy(Account.Name, isDescending)
    .toList();
apex
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

ParameterTypeDescription
fieldSObjectFieldField token to sort by
sortDescendingBooleanWhen true, sorts DESCENDING; otherwise ASCENDING
nullsLastBooleanWhen true, places nulls last; otherwise places nulls first

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
Boolean isDescending = true;
Boolean isNullsLast = true;
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .orderBy(Account.Name, isDescending, isNullsLast)
    .toList();
apex
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

ParameterTypeDescription
fieldNameStringA field API name, such as Name or Account.Owner.Name, or a list of sort items

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif the text is not blank and is not a list of sort items

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .orderBy('CreatedDate').descending()
    .toList();
apex
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

ParameterTypeDescription
fieldNameStringA field API name, such as Name or Account.Owner.Name
sortDescendingBooleanWhen true, sorts DESCENDING; otherwise ASCENDING

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif the text is not blank and is not such a list

Example

apex
Boolean isDescending = false;
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .orderBy('CreatedDate', isDescending)
    .toList();
apex
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

ParameterTypeDescription
fieldNameStringA field API name, such as Name or Account.Owner.Name
sortDescendingBooleanWhen true, sorts DESCENDING; otherwise ASCENDING
nullsLastBooleanWhen true, places nulls last; otherwise places nulls first

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif the text is not blank and is not such a list

Example

apex
Boolean isDescending = true;
Boolean isNullsLast = false;
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .orderBy('CreatedDate', isDescending, isNullsLast)
    .toList();

orderByCount ​

apex
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

ParameterTypeDescription
fieldSObjectFieldThe field whose COUNT orders the grouped rows
sortDescendingBooleanWhen true, sorts DESCENDING (largest groups first); otherwise ASCENDING

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif field is null

Example

apex
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 ​

apex
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

ParameterTypeDescription
parentFieldStringA field API name, such as Name or Account.Owner.Name

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif the text is not blank and is not a field name or a path through parent records, such as Account.Owner.Name

Example

apex
List<Contact> contacts = QRY_Builder.selectFrom(Contact.SObjectType)
    .relatedField('Account.Owner.Name')
    .toList();

relatedFields ​

apex
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

ParameterTypeDescription
parentFieldsListA list of field API names, such as Name or Account.Owner.Name

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif 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

apex
List<Contact> contacts = QRY_Builder.selectFrom(Contact.SObjectType)
    .relatedFields(new List<String>{'Account.Name', 'Account.Industry'})
    .toList();

rollup ​

apex
global QRY_Builder.Builder rollup()

Flags the GROUP BY clause as ROLLUP for subtotals.

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<QRY_Builder.AggregateRow> results = QRY_Builder.selectFrom(Opportunity.SObjectType)
    .groupBy(Opportunity.StageName)
    .groupBy(Opportunity.AccountId)
    .sum(Opportunity.Amount)
    .rollup()
    .toAggregateList();

selectAllFields ​

apex
global QRY_Builder.Builder selectAllFields()

Configures the query to select ALL fields on the object.

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .selectAllFields()
    .withLimit(10)
    .toList();

stripInaccessible ​

apex
global QRY_Builder.Builder stripInaccessible()

Strips inaccessible fields from results.

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .stripInaccessible()
    .toList();

subselect ​

apex
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

ParameterTypeDescription
childQueryQRY_Builder.BuilderConfigured Builder for the child object
relationshipNameStringThe child relationship API name (e.g., 'Contacts' or 'Account.Contacts')

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif 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

apex
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 ​

apex
global QRY_Builder.Builder sum(SObjectField field)

Applies a SUM aggregate function.

Parameters

ParameterTypeDescription
fieldSObjectFieldThe field to aggregate

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<QRY_Builder.AggregateRow> rows = QRY_Builder.selectFrom(Opportunity.SObjectType)
    .groupBy(Opportunity.StageName)
    .sum(Opportunity.Amount)
    .toAggregateList();
Decimal firstStageTotal = rows[0].getDecimal('sum_Amount');
apex
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

ParameterTypeDescription
fieldSObjectFieldThe field to sum
aliasStringThe result alias; must be a bare identifier, unique across the aliased selections

Returns QRY_Builder.Builder — Builder for chaining

Throws

ExceptionDescription
IllegalArgumentExceptionif 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

apex
.sum(Opportunity.Amount, 'pipelineTotal')

suppressPerformanceLogging ​

apex
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

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .suppressPerformanceLogging()
    .toList();

toAggregateList ​

apex
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

ExceptionDescription
QueryExceptionWith 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.IllegalStateExceptionIn 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

apex
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 ​

apex
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

ExceptionDescription
QueryExceptionWith 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.IllegalStateExceptionWith bypassSharing() alone, under user mode. The rows are fetched later, so the fields the running user cannot read cannot be removed. Add withSystemMode().

Example

apex
Database.Cursor cursor = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Type).equals('Customer')
    .toCursor();

toList ​

apex
global List<SObject> toList()

Executes the query and returns a List of SObjects.

Returns SObject — List results

Throws

ExceptionDescription
QueryExceptionWith 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.IllegalStateExceptionIn 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.IllegalStateExceptionWith 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

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Industry).equals('Technology')
    .toList();

toQueryLocator ​

apex
global Database.QueryLocator toQueryLocator()

Returns a Database.QueryLocator for batch processing.

Returns Database.QueryLocator — Database.QueryLocator

Throws

ExceptionDescription
QueryExceptionWith 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.IllegalStateExceptionWith 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

apex
Database.QueryLocator locator = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Type).equals('Customer')
    .toQueryLocator();

toSoql ​

apex
global String toSoql()

Generates and returns the SOQL string without executing it.

Returns String — The built SOQL query string

Example

apex
String soql = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Industry).equals('Technology')
    .toSoql();

usingScope ​

apex
global QRY_Builder.Builder usingScope(QRY_Builder.Scope scopeValue)

Filters records by visibility scope using USING SCOPE clause.

Parameters

ParameterTypeDescription
scopeValueQRY_Builder.ScopeThe scope to apply

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .usingScope(QRY_Builder.Scope.MINE)
    .toList();

withCache ​

apex
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

ParameterTypeDescription
ttlSecondsIntegerTime-to-live in seconds for Platform Cache; ignored in memory; null requests no caching

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
Account account = (Account)QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Id).equals(accountId)
    .withSystemMode()
    .withSharing()
    .withCache(300)
    .getFirst();
apex
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

ParameterTypeDescription
scopeUTIL_Cache.ScopeWhere results may be kept; null means no caching
ttlSecondsIntegerTime-to-live in seconds for Platform Cache; ignored in memory; null uses the default

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> parents = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Id).isIn(parentIds)
    .withCache(UTIL_Cache.Scope.IN_TRANSACTION, null)
    .toList();

withDataCategory ​

apex
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

ParameterTypeDescription
groupNameStringThe data category group API name, such as Geography__c

Returns QRY_Builder.DataCategoryBuilder — DataCategoryBuilder for operator selection

Throws

ExceptionDescription
IllegalArgumentExceptionif groupName is blank, or is not a single API name, such as Name

Example

apex
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 ​

apex
global QRY_Builder.Builder withLimit(Integer recordLimit)

Sets the maximum number of records to return (LIMIT).

Parameters

ParameterTypeDescription
recordLimitIntegerMaximum number of records

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .withLimit(100)
    .toList();

withOffset ​

apex
global QRY_Builder.Builder withOffset(Integer rowNumber)

Sets the record offset (OFFSET).

Parameters

ParameterTypeDescription
rowNumberIntegerNumber of records to skip

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .withLimit(25)
    .withOffset(50)
    .toList();

withoutCache ​

apex
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

apex
List<Account> fresh = new SEL_Account().query.withoutCache().condition(Account.Id).isIn(ids).toList();

withoutSecurity ​

apex
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

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .withoutSecurity()
    .toList();

withSharing ​

apex
global QRY_Builder.Builder withSharing()

Enforces sharing rules using a with sharing proxy class.

Returns QRY_Builder.Builder — Builder for chaining

Example

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .withSharing()
    .toList();

withSystemMode ​

apex
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

apex
TriggerSetting__mdt setting = (TriggerSetting__mdt)QRY_Builder.selectFrom(TriggerSetting__mdt.SObjectType)
    .withSystemMode()
    .condition(TriggerSetting__mdt.SObjectType__c).equals('Account')
    .getFirst();

withUserMode ​

apex
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

apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .withUserMode()
    .toList();

Constructors ​

ConstructorDescription
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() ​

apex
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

apex
QRY_Builder.Builder query = new QRY_Builder.Builder();

Builder(SObjectType sObjectType) ​

apex
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

ParameterTypeDescription
sObjectTypeSObjectTypeThe SObject to query

Example

apex
QRY_Builder.Builder query = new QRY_Builder.Builder(Account.SObjectType);

Properties ​

PropertyDescription
global SObjectType objectTypeThe object this builder reads, as passed to QRY_Builder.selectFrom.

objectType ​

apex
global SObjectType objectType

Type: 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.