Query.apex

  • Docs
  • Tutorials
Docs Menu
  • Query class
    • Constructor
    • Result
    • Field Selection
    • Condition
    • Subquery
    • Aggregate Functions

Result Guide

Methods to get the Query result

run

Run the query as if running Database.query().

public List run()

Returns a list of SObject.

Alias to toSObjectList().

List accounts =
    new Query('Account').
    run();

fetch

Fetch a subset of the result.

public SObject fetch()

Fetch the first SObject from the result.

Returns an SObject.

Account account =
    (Account)
    new Query('Account').
    fetch();

public SObject fetch(Integer n)

Fetch the n elements from the result.

n: Indicates the number of elements.

Returns an SObject.

Account account =
    (Account)
    new Query('Account').
    fetch(2);

public List fetch(Integer first, Integer last)

Fetch a subset of result in the range [first, last).

Returns a list of SObject.

List accounts =
    new Query('Account').
    fetch(2, 4);

toSObjectList

Run the query as if running Database.query().

public List toSObjectList()

Returns a list of SObject.

Alias to run().

List accounts =
    new Query('Account').
    toSObjectList();

toIdList

Run the query and return the Id list of the result.

public List toIdList()

Returns a list of Id.

List accounts =
    new Query('Account').
    toIdList();

getQueryLocator

Get the QueryLocator that can be used for Batch Apex.

public Database.QueryLocator getQueryLocator()

Returns a Database.QueryLocator.

Database.QueryLocator locator =
    new Query('Account').
    selectAllFields().
    getQueryLocator();

aggregate

Get the result of the aggregated query.

Can only be used with aggregate functions.

public List aggregate()

Get the result of the aggregated query.

Returns a List of AggregateResult.

The returned list is guaranteed to be non-empty.

List result =
    new Query('Account').
    count('Name').
    aggregate();

toQueryString

Get an executable SOQL string that can be used in Dateabase.query().

public String toQueryString()

Returns an executable SOQL string.

String queryStr = new Query('Account').
    selectAllFields().
    run();
List accounts = Datebase.query(queryStr);

Contribute on Github! Edit this section.