Skip to main content

Overview

The Query class provides a fluent, chainable API for building and executing SOQL queries. It supports query construction, execution, streaming, bulk operations, and automatic record fetching.

Creating Queries

From Connection

Create a query directly from a connection object.
const query = conn.query('SELECT Id, Name FROM Account WHERE Industry = \'Technology\'');

From SObject

Use SObject methods to create queries with type safety.
const query = conn.sobject('Account').find({ Industry: 'Technology' });

Query Building Methods

Query building methods are chainable and allow you to construct complex queries programmatically.

select()

Select fields to include in the result.
const query = conn.sobject('Account')
  .select('Id, Name, Industry');
fields
string | string[] | object
Fields to select. Can be:
  • Comma-separated string
  • Array of field names
  • Object with field projection config
  • ’*’ for all fields

where()

Filter records by conditions.
const query = conn.sobject('Account')
  .select('Id, Name')
  .where({ Industry: 'Technology' });
conditions
QueryCondition | string
required
Query conditions object or SOQL WHERE clause string

limit()

Limit the number of records returned.
const query = conn.sobject('Account')
  .select('Id, Name')
  .limit(10);
limit
number
required
Maximum number of records to return

skip() / offset()

Skip a specified number of records.
const query = conn.sobject('Account')
  .select('Id, Name')
  .limit(10)
  .skip(20); // Skip first 20 records
offset
number
required
Number of records to skip

sort() / orderby()

Sort query results.
const query = conn.sobject('Account')
  .select('Id, Name')
  .sort({ Name: 'ASC', CreatedDate: 'DESC' });
sort
object | string | array
required
Sort configuration:
  • Object: { fieldName: 'ASC' | 'DESC' }
  • String + direction: sort('Name', 'ASC')
  • Array: [['Name', 'ASC'], ['CreatedDate', 'DESC']]

include()

Include child relationship records in the query.
const query = conn.sobject('Account')
  .select('Id, Name')
  .include('Contacts');

const accounts = await query;
accounts.forEach(account => {
  console.log(account.Contacts.records);
});
childRelName
string
required
Child relationship name (e.g., ‘Contacts’, ‘Opportunities’)
conditions
QueryCondition
Filter conditions for child records
fields
string | string[]
Fields to select from child records
options
object
result
SubQuery
Returns a SubQuery instance that can be chained or ended with .end()

Query Execution

execute() / exec() / run()

Execute the query and fetch results.
const query = conn.sobject('Account')
  .select('Id, Name')
  .where({ Industry: 'Technology' })
  .limit(100);

const records = await query.execute();
records.forEach(record => console.log(record.Name));
options
QueryOptions

Promise Interface

Queries implement the Promise interface and auto-execute when awaited.
// Auto-executes when awaited
const records = await conn.sobject('Account')
  .select('Id, Name')
  .where({ Industry: 'Technology' });

// Or use .then()
conn.sobject('Account')
  .select('Id, Name')
  .where({ Industry: 'Technology' })
  .then(records => {
    console.log(records);
  })
  .catch(err => {
    console.error(err);
  });

Query Options

autoFetch()

Enable automatic fetching of all records.
const query = conn.sobject('Account')
  .select('Id, Name')
  .autoFetch(true) // Fetch all records across multiple API calls
  .maxFetch(50000); // Up to 50,000 records

const allRecords = await query;
console.log(`Fetched ${allRecords.length} records`);
autoFetch
boolean
required
Enable (true) or disable (false) automatic fetching

maxFetch()

Set maximum number of records to fetch.
const query = conn.sobject('Account')
  .select('Id, Name')
  .maxFetch(5000); // Fetch up to 5000 records
maxFetch
number
required
Maximum number of records to fetch

scanAll()

Include deleted and archived records.
const query = conn.sobject('Account')
  .select('Id, Name, IsDeleted')
  .scanAll(true); // Uses queryAll instead of query

const allRecords = await query; // Includes deleted records
scanAll
boolean
required
Enable (true) or disable (false) scanning all records

Streaming

stream()

Get a readable stream of query results.
const stream = conn.sobject('Account')
  .select('Id, Name')
  .where({ Industry: 'Technology' })
  .stream('record');

stream.on('data', record => {
  console.log(record.Name);
});

stream.on('end', () => {
  console.log('Done');
});

stream.on('error', err => {
  console.error(err);
});
type
'record' | 'csv'
Stream type (default: ‘csv’)
  • ‘record’: Stream individual record objects
  • ‘csv’: Stream CSV formatted data
result
Readable
Node.js Readable stream

pipe()

Pipe query results to a writable stream.
conn.sobject('Account')
  .select('Id, Name')
  .pipe(process.stdout);

Query Information

toSOQL()

Generate SOQL string from the query.
const query = conn.sobject('Account')
  .select('Id, Name')
  .where({ Industry: 'Technology' })
  .limit(10);

const soql = await query.toSOQL();
console.log(soql);
// "SELECT Id, Name FROM Account WHERE Industry = 'Technology' LIMIT 10"
result
string
SOQL query string

explain()

Get query execution plan.
const query = conn.sobject('Account')
  .select('Id, Name')
  .where({ Industry: 'Technology' });

const plan = await query.explain();

plan.plans.forEach(plan => {
  console.log('Leading operation:', plan.leadingOperationType);
  console.log('Cardinality:', plan.cardinality);
  console.log('Relative cost:', plan.relativeCost);
  console.log('Fields:', plan.fields);
});
result
QueryExplainResult

Bulk Operations

destroy() / delete() / del()

Bulk delete queried records.
const results = await conn.sobject('Account')
  .find({ Industry: 'Test' })
  .destroy();

results.forEach(result => {
  console.log(result.id, result.success);
});
options
QueryDestroyOptions
result
SaveResult[]
Array of save results for deleted records

update()

Bulk update queried records.
const results = await conn.sobject('Account')
  .find({ Industry: 'Technology' })
  .update(record => ({
    ...record,
    Description: `${record.Name} - Technology Account`
  }));
mapping
function | object
required
Either:
  • Function that takes a record and returns updated fields
  • Object with fields to update on all records
options
QueryUpdateOptions
result
SaveResult[]
Array of save results for updated records

Query Events

Queries emit events during execution.
const query = conn.sobject('Account')
  .select('Id, Name')
  .where({ Industry: 'Technology' });

query.on('record', (record, index) => {
  console.log(`Record ${index}:`, record.Name);
});

query.on('end', () => {
  console.log('Query completed');
});

query.on('error', err => {
  console.error('Query error:', err);
});

query.on('fetch', () => {
  console.log('Fetched batch of records');
});

query.execute();

Events

record
event
Emitted for each record fetchedCallback parameters:
  • record - The record object
  • index - Record index (0-based)
  • query - Query instance
end
event
Emitted when query completes
error
event
Emitted on query errorCallback parameters:
  • error - Error object
fetch
event
Emitted when a batch of records is fetched
response
event
Emitted with final query responseCallback parameters:
  • response - Query result (type depends on response target)
  • query - Query instance

Query Properties

totalSize

Total number of records matching the query.
const query = conn.sobject('Account')
  .select('Id')
  .where({ Industry: 'Technology' });

await query.execute();
console.log(`Total records: ${query.totalSize}`);

totalFetched

Number of records fetched so far.
const query = conn.sobject('Account')
  .select('Id')
  .maxFetch(1000);

await query.execute();
console.log(`Fetched: ${query.totalFetched}`);

records

Array of fetched records.
const query = conn.sobject('Account')
  .select('Id, Name')
  .limit(10);

await query.execute();
query.records.forEach(record => console.log(record.Name));

Build docs developers (and LLMs) love