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.
String Fields
Array Fields
Nested Fields
Wildcard
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.
Simple Condition
Multiple Conditions
OR Condition
Complex Operators
SOQL String
const query = conn . sobject ( 'Account' )
. select ( 'Id, Name' )
. where ({ Industry: 'Technology' });
conditions
QueryCondition | string
required
Query conditions object or SOQL WHERE clause string
$eq - Equals (default if no operator specified)
$ne - Not equals
$gt - Greater than
$gte - Greater than or equal to
$lt - Less than
$lte - Less than or equal to
$like - LIKE pattern matching
$nlike - NOT LIKE pattern matching
$in - IN (value is in list)
$nin - NOT IN
$includes - INCLUDES (for multi-select picklists)
$excludes - EXCLUDES (for multi-select picklists)
$exists - Field has a value (true) or is null (false)
$or - Logical OR
$and - Logical AND
limit()
Limit the number of records returned.
const query = conn . sobject ( 'Account' )
. select ( 'Id, Name' )
. limit ( 10 );
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
Number of records to skip
sort() / orderby()
Sort query results.
Object Syntax
Two Parameters
Array Syntax
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.
Basic Include
With Conditions
With Fields
With Options
Nested Include
const query = conn . sobject ( 'Account' )
. select ( 'Id, Name' )
. include ( 'Contacts' );
const accounts = await query ;
accounts . forEach ( account => {
console . log ( account . Contacts . records );
});
Child relationship name (e.g., ‘Contacts’, ‘Opportunities’)
Filter conditions for child records
Fields to select from child records
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 ));
Automatically fetch all records across multiple queries (default: false)
Maximum number of records to fetch (default: 10000)
Include deleted and archived records (default: false)
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` );
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
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
Enable (true) or disable (false) scanning all records
Streaming
stream()
Get a readable stream of query results.
Record Stream
CSV Stream
Process Large Dataset
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 );
});
Stream type (default: ‘csv’)
‘record’: Stream individual record objects
‘csv’: Stream CSV formatted data
pipe()
Pipe query results to a writable stream.
conn . sobject ( 'Account' )
. select ( 'Id, Name' )
. pipe ( process . stdout );
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"
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 );
});
Array of execution plan objects Type: ‘Index’, ‘TableScan’, ‘Sharing’, or ‘Other’
Estimated number of records
Relative cost of the operation
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 );
});
Allow using Bulk API (default: true)
Number of records to trigger Bulk API (default: 200)
Bulk API version to use (default: 1)
Array of save results for deleted records
update()
Bulk update queried records.
Update Mapping Function
Update Object
With Options
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
Allow using Bulk API (default: true)
Number of records to trigger Bulk API (default: 200)
Bulk API version to use (default: 1)
Skip template evaluation for update object
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
Emitted for each record fetched Callback parameters:
record - The record object
index - Record index (0-based)
query - Query instance
Emitted when query completes
Emitted on query error Callback parameters:
Emitted when a batch of records is fetched
Emitted with final query response Callback 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 ));