Skip to content

Salesforce

Salesforce CRM as SQL: SOQL pushdown, Bulk API 2.0, describe-typed objects and a free ID toolkit

Connector software
Free and open source
Service credentials
Required
Use with an agent

Install the Orchard skill in your project to help your agent find connectors, configure them, and verify SQL results.

npx skills add Query-farm/vgi-skills --skill orchard

Copy this request into your coding agent to get started.

Use https://query.farm/products/orchard/connectors/salesforce/index.md to help me query Salesforce with DuckDB or Haybarn 2.0.1 and VGI protocol 3.4. Ask only for missing details about the result I need or whether I want local execution, self-hosting or Query Farm hosting. Check the connector's actual hosting availability, credentials and input requirements. Read one format of each needed reference and the exact object declarations before writing SQL. Use a released connector, and distinguish a saved example result from anything you actually execute. If you cannot run the query, tell me what remains to verify.

Compare sales pipeline value by stage

Uses your connected account. Set up the connector and credentials to run it with your data.

SELECT stage_name, deals, total
FROM salesforce.main.soql('SELECT StageName, COUNT(Id) deals, SUM(Amount) total FROM Opportunity GROUP BY StageName')
WHERE deals > 1
ORDER BY total DESC

Quick start

Choose where to run Salesforce, then follow the steps below.

The connector runs alongside DuckDB or Haybarn. No Query Farm account is needed.

1. Install the vgi extension

Run this in your SQL client. On DuckDB, keep FROM query_farm on LOAD in later sessions.

setup.sql
SET allow_extension_repositories = 'allowed';

CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
    WITH PREFIX 'https://duckdb-extensions.query.farm';

INSTALL vgi FROM query_farm;
LOAD vgi FROM query_farm;

2. Attach the connector

Attach the release directly

Downloads the latest release for your platform and caches it locally.

ATTACH 'salesforce' AS salesforce (
  TYPE vgi,
  LOCATION 'github-auto://Query-farm/vgi-salesforce'
);

3. Add service credentials

After attaching, create the secret for the service you want to query in the same SQL session. Replace the placeholders with your service settings.

salesforce credentials

Salesforce org (instance_url) plus OAuth: JWT bearer (client_id + username + private_key), client credentials (client_id + client_secret), refresh token, or a pre-issued access_token. Username/password is not supported.

Get these credentials →
secret.sql
CREATE SECRET salesforce (
    TYPE salesforce,
    instance_url  '<instance_url>',
    login_url     '<login_url>',
    api_version   '<api_version>',
    client_id     '<client_id>',
    username      '<username>',
    private_key   '<PRIVATE_KEY>',  -- secret
    client_secret '<SALESFORCE_CLIENT_SECRET>',  -- secret
    refresh_token '<REFRESH_TOKEN>',  -- secret
    access_token  '<ACCESS_TOKEN>'  -- secret
);
Credential fields and requirements →

4. Run a query

query.sql
SELECT stage_name, deals, total
FROM salesforce.main.soql('SELECT StageName, COUNT(Id) deals, SUM(Amount) total FROM Opportunity GROUP BY StageName')
WHERE deals > 1
ORDER BY total DESC
More example queries →
Technical details
Verified connector release
v0.2.0
Engine
2.0.1
VGI protocol
3.4.0
Verified on
December 1, 2026
Release notes on GitHub
Pin a version for production

When running the connector yourself, keep a specific release until you’re ready to upgrade. Replace the ATTACH statement above with this one and follow the same extension and credential setup.

Attach the release directly

Uses the verified release each time you attach the connector.

ATTACH 'salesforce' AS salesforce (
  TYPE vgi,
  LOCATION 'github-auto://Query-farm/[email protected]'
);

Overview

Salesforce CRM as SQL: SOQL and Bulk API 2.0 scans with DuckDB filters pushed into SOQL, describe-typed object views, delete-aware incremental helpers, org metadata and limits, plus a credential-free Salesforce ID toolkit.

ATTACH options

objects
Comma-separated object API names to expose as sobjects.<Object> views, e.g. 'Account,Contact,Opportunity,Invoice__c'. Empty (the default) gives the functions and meta tables only; browse meta.objects, then re-attach.VARCHAR
quota_guard_pct
Fail a scan before an API call once the org's daily API usage (Sforce-Limit-Info) reaches this percentage (1-100).INTEGER
state_dir
Directory for the Bulk/REST scan journal used by resume := true and meta.jobs (default $XDG_STATE_HOME/vgi-salesforce).VARCHAR

Catalog

Everything salesforce exposes once attached — read straight from the worker's released build.

salesforce 2 schemas
main 14 functions

Salesforce functions: a credential-free ID toolkit, typed SOQL scans with pushdown, per-id lookups and incremental sync.

Schema examples (12)
Examples (12)

15- and 18-character forms of the same id collapse to one join key

SELECT salesforce.main.id18(opportunity_id) AS join_key, count(*) AS rows
FROM (VALUES ('001Dn00000AbCdE'), ('001Dn00000AbCdEIAV')) t(opportunity_id)
GROUP BY join_key;

Shorten an API id to its report form

SELECT salesforce.main.id15('001Dn00000AbCdEIAV') AS short_id;

Count ids by object-type prefix

SELECT salesforce.main.key_prefix(what_id) AS prefix, count(*) AS tasks
FROM (VALUES ('006Dn000001aBcD'), ('001Dn00000AbCdE')) t(what_id)
GROUP BY prefix
ORDER BY prefix;

Resolve polymorphic WhatIds to object names

SELECT salesforce.main.object_of(what_id) AS target, count(*) AS tasks
FROM (VALUES ('006Dn000001aBcD'), ('500Dn000002XyZq'), ('006Dn000003aBcE')) t(what_id)
GROUP BY target
ORDER BY target;
8 more examples

Count valid and invalid ids in an export

SELECT count(*) FILTER (WHERE salesforce.main.is_valid_id(id)) AS valid,
  count(*) FILTER (WHERE NOT salesforce.main.is_valid_id(id)) AS invalid
FROM (VALUES ('001Dn00000AbCdEIAV'), ('001Dn00000AbCdEAAA'), ('n/a')) t(id);

Build a WHERE clause from a value with a quote in it

SELECT 'LastName = ' || salesforce.main.soql_literal(last_name) AS where_clause
FROM (VALUES ('O''Brien')) t(last_name);

Pipeline by stage, aggregated by Salesforce

SELECT stage_name, deals, total
FROM salesforce.main.soql('SELECT StageName, COUNT(Id) deals, SUM(Amount) total FROM Opportunity GROUP BY StageName')
WHERE deals > 1
ORDER BY total DESC;

Contacts with their account and the account owner (relationship paths flatten to columns)

SELECT name, account_name, account_owner_name
FROM salesforce.main.soql('SELECT Name, Account.Name, Account.Owner.Name FROM Contact WHERE Email != null')
ORDER BY name;

Open pipeline by stage (only StageName and Amount are fetched)

SELECT stage_name, count(*) AS deals, sum(amount) AS pipeline
FROM salesforce.main.query_object('Opportunity', fields := ['StageName', 'Amount'])
WHERE NOT is_closed
GROUP BY stage_name
ORDER BY pipeline DESC;

Incremental extract: accounts changed since a watermark

SELECT id, name, system_modstamp
FROM salesforce.main.query_object('Account', fields := ['Id', 'Name', 'SystemModstamp'], modified_after := TIMESTAMPTZ '2026-01-01 00:00:00+00')
ORDER BY system_modstamp;

Custom fields of Opportunity and their SQL columns

SELECT name, sf_type, column_name, duckdb_type
FROM salesforce.main.describe_fields('Opportunity')
WHERE custom
ORDER BY name;

Polymorphic lookups on Task (WhatId, WhoId …)

SELECT name, reference_to
FROM salesforce.main.describe_fields('Task')
WHERE sf_type = 'reference' AND len(reference_to) > 1
ORDER BY name;
Scalar functions
id15 (sf_id VARCHAR) 2 examples

Convert an 18-character Salesforce id to the 15-character case-sensitive form (validating its checksum)

Arguments
sf_id VARCHAR
A Salesforce record id as text, in its short case-sensitive form or its long case-safe form; NULL in, NULL out.
ReturnsVARCHAR
Examples (2)

Shorten an API id to its report form

SELECT salesforce.main.id15('001Dn00000AbCdEIAV') AS short_id;
SELECT salesforce.main.id15('001Dn00000AbCdEIAV') AS id;
Link
id18 (sf_id VARCHAR) 2 examples

Convert a 15-character case-sensitive Salesforce id to the 18-character case-safe form

Arguments
sf_id VARCHAR
A Salesforce record id as text, in its short case-sensitive form or its long case-safe form; NULL in, NULL out.
ReturnsVARCHAR
Examples (2)

15- and 18-character forms of the same id collapse to one join key

SELECT salesforce.main.id18(opportunity_id) AS join_key, count(*) AS rows
FROM (VALUES ('001Dn00000AbCdE'), ('001Dn00000AbCdEIAV')) t(opportunity_id)
GROUP BY join_key;
SELECT salesforce.main.id18('001Dn00000AbCdE') AS a,
  salesforce.main.id18('001Dn00000AbCdEIAV') AS b,
  salesforce.main.id18(lower('001Dn00000AbCdEIAV')) AS repaired;
Link
is_valid_id (sf_id VARCHAR) 2 examples

True when a value is a well-formed Salesforce id (an 18-character id must carry a matching checksum)

Arguments
sf_id VARCHAR
A Salesforce record id as text, in its short case-sensitive form or its long case-safe form; NULL in, NULL out.
ReturnsBOOLEAN
Examples (2)

Count valid and invalid ids in an export

SELECT count(*) FILTER (WHERE salesforce.main.is_valid_id(id)) AS valid,
  count(*) FILTER (WHERE NOT salesforce.main.is_valid_id(id)) AS invalid
FROM (VALUES ('001Dn00000AbCdEIAV'), ('001Dn00000AbCdEAAA'), ('n/a')) t(id);
SELECT salesforce.main.is_valid_id('001Dn00000AbCdEIAV') AS good,
  salesforce.main.is_valid_id('001Dn00000AbCdEAAA') AS bad,
  salesforce.main.is_valid_id('n/a') AS junk;
Link
key_prefix (sf_id VARCHAR) 2 examples

The 3-character key prefix of a Salesforce id (the object type code, e.g. '006' for Opportunity)

Arguments
sf_id VARCHAR
A Salesforce record id as text, in its short case-sensitive form or its long case-safe form; NULL in, NULL out.
ReturnsVARCHAR
Examples (2)

Count ids by object-type prefix

SELECT salesforce.main.key_prefix(what_id) AS prefix, count(*) AS tasks
FROM (VALUES ('006Dn000001aBcD'), ('001Dn00000AbCdE')) t(what_id)
GROUP BY prefix
ORDER BY prefix;
SELECT salesforce.main.key_prefix('006Dn000001aBcD') AS p;
Link
object_of (sf_id VARCHAR) 2 examples

The standard object an id belongs to, from its key prefix (NULL for custom objects)

Arguments
sf_id VARCHAR
A Salesforce record id as text, in its short case-sensitive form or its long case-safe form; NULL in, NULL out.
ReturnsVARCHAR
Examples (2)

Resolve polymorphic WhatIds to object names

SELECT salesforce.main.object_of(what_id) AS target, count(*) AS tasks
FROM (VALUES ('006Dn000001aBcD'), ('500Dn000002XyZq'), ('006Dn000003aBcE')) t(what_id)
GROUP BY target
ORDER BY target;
SELECT salesforce.main.object_of('006Dn000001aBcD') AS a,
  salesforce.main.object_of('00QDn000001aBcD') AS b,
  salesforce.main.object_of('a0XDn000001aBcD') AS c;
Link
soql_literal (v VARCHAR) 2 examples

Quote and escape a value as a SOQL string literal, for building WHERE clauses safely

Arguments
v VARCHAR
Value to quote; NULL in, NULL out.
ReturnsVARCHAR
Examples (2)

Build a WHERE clause from a value with a quote in it

SELECT 'LastName = ' || salesforce.main.soql_literal(last_name) AS where_clause
FROM (VALUES ('O''Brien')) t(last_name);
SELECT salesforce.main.soql_literal('O''Brien') AS lit;
Link
Table functions
deleted_ids (object_name VARCHAR, start_date TIMESTAMP WITH TIME ZONE, end_date TIMESTAMP WITH TIME ZONE) 1 example

Ids of records of an object deleted in a time window (REST getDeleted); errors outside recycle-bin retention

Arguments
object_name VARCHAR
Object API name (must be replicateable, see meta.objects).
start_date TIMESTAMP WITH TIME ZONE
Window start (inclusive). Longer than 30 days is split automatically.
end_date TIMESTAMP WITH TIME ZONE
Window end.
Returns columns
sf_id VARCHAR
Deleted record id.
deleted_date TIMESTAMP WITH TIME ZONE
When the record was deleted.
Example

Opportunities deleted this week (to remove from a replica)

SELECT sf_id, deleted_date
FROM salesforce.main.deleted_ids('Opportunity', now() - INTERVAL 7 DAY, now())
ORDER BY deleted_date;
Link
describe_fields (object_name VARCHAR) 2 examples

Every field of one object from describe: names, types, lengths, flags, references, formulas and the DuckDB column

Arguments
object_name VARCHAR
Object API name, e.g. 'Opportunity'.
Returns columns
name VARCHAR
Field API name.
label VARCHAR
Label.
sf_type VARCHAR
Salesforce field type.
soap_type VARCHAR
SOAP type (xsd:string …).
length INTEGER
Maximum length for text fields.
precision INTEGER
Total digits for numbers.
scale INTEGER
Digits after the decimal point.
nillable BOOLEAN
Can be empty.
createable BOOLEAN
Settable on insert.
updateable BOOLEAN
Settable on update.
filterable BOOLEAN
Usable in SOQL WHERE.
sortable BOOLEAN
Usable in ORDER BY.
custom BOOLEAN
Custom field.
calculated BOOLEAN
Formula or roll-up field.
formula VARCHAR
Formula text for calculated fields.
reference_to VARCHAR[]
Objects a lookup can point to (several for polymorphic fields).
relationship_name VARCHAR
Relationship name for paths (Account in Account.Name).
compound_field_name VARCHAR
Compound (address/geolocation) field this is a component of.
column_name VARCHAR
DuckDB column name in query_object / sobjects views (null if not exposed).
duckdb_type VARCHAR
DuckDB type (null for base64 fields, which are not exposed).
Examples (2)

Custom fields of Opportunity and their SQL columns

SELECT name, sf_type, column_name, duckdb_type
FROM salesforce.main.describe_fields('Opportunity')
WHERE custom
ORDER BY name;

Polymorphic lookups on Task (WhatId, WhoId …)

SELECT name, reference_to
FROM salesforce.main.describe_fields('Task')
WHERE sf_type = 'reference' AND len(reference_to) > 1
ORDER BY name;
Link
lookup (sf_id VARCHAR, fields := VARCHAR[], object_name := VARCHAR) 1 example

Typed per-row record lookup by id for one object (fixed at bind), batched 200 ids per API call

Positional arguments
sf_id VARCHAR
Record id (15 or 18 characters); rows whose id is not a visible record produce no output.
Named arguments
fields := VARCHAR[]
Fields to return (direct fields only, no relationship paths); NULL returns every field. · default null
object_name := VARCHAR
Object API name; fixes the typed output columns at bind (required).
Returns columns
id VARCHAR
The record id (18 characters).
stage_name VARCHAR
StageName (picklist).
amount DECIMAL(16,2)
Amount (currency, precision and scale from describe).
close_date DATE
CloseDate.
is_won BOOLEAN
IsWon.
system_modstamp TIMESTAMP WITH TIME ZONE
Last system change, the incremental watermark.
stage_name VARCHAR
A plain field, typed from describe.
account_owner_name VARCHAR
A parent relationship path, flattened with underscores.
expr0 BIGINT
An unaliased aggregate, numbered as the API numbers it.
total DOUBLE
An aliased SUM/AVG (MIN/MAX keep the field's type).
Returns columns · depends on the arguments
Object scan (query_object, sobjects views, lookup)
id VARCHAR
The record id (18 characters).
stage_name VARCHAR
StageName (picklist).
amount DECIMAL(16,2)
Amount (currency, precision and scale from describe).
close_date DATE
CloseDate.
is_won BOOLEAN
IsWon.
system_modstamp TIMESTAMP WITH TIME ZONE
Last system change, the incremental watermark.
SOQL query (soql)
stage_name VARCHAR
A plain field, typed from describe.
account_owner_name VARCHAR
A parent relationship path, flattened with underscores.
expr0 BIGINT
An unaliased aggregate, numbered as the API numbers it.
total DOUBLE
An aliased SUM/AVG (MIN/MAX keep the field's type).
Example

Enrich tasks with their opportunity's name and amount

SELECT t.subject, o.name, o.amount
FROM (VALUES ('Call', '006Dn000001aBcD')) t(subject, what_id),
     LATERAL salesforce.main.lookup(t.what_id, object_name := 'Opportunity', fields := ['Name', 'Amount']) o;
Link
picklist_values (object_name VARCHAR, field_name VARCHAR) 1 example

The picklist values of (object, field) pairs, one row per value, from describe

Arguments
object_name VARCHAR
Object API name.
field_name VARCHAR
Picklist or multi-select picklist field API name.
Returns columns
value VARCHAR
API value stored on records.
label VARCHAR
Display label.
active BOOLEAN
Whether the value can be chosen.
default_value BOOLEAN
Whether it is the field's default.
Example

The active opportunity stages

SELECT value, label
FROM salesforce.main.picklist_values('Opportunity', 'StageName')
WHERE active
ORDER BY value;
Link
query_object (object_name VARCHAR, api := VARCHAR, bulk_page_size := BIGINT, bulk_threshold := BIGINT, fields := VARCHAR[], include_deleted := BOOLEAN, max_rows := BIGINT, modified_after := TIMESTAMP WITH TIME ZONE, modified_before := TIMESTAMP WITH TIME ZONE, order_by := VARCHAR, resume := BOOLEAN, where_clause := VARCHAR) 2 examples

Rows of one Salesforce object, typed from its describe, with SQL filters, projection and LIMIT pushed into SOQL

Positional arguments
object_name VARCHAR
Object API name, e.g. 'Opportunity' or 'Invoice__c'.
Named arguments
api := VARCHAR
'auto' (REST, switching to Bulk API 2.0 above bulk_threshold rows), 'rest' or 'bulk'. · default "auto"
bulk_page_size := BIGINT
Records per Bulk API 2.0 results page (maxRecords); each page is one Sforce-Locator step. · default 50000
bulk_threshold := BIGINT
In api 'auto', the totalSize above which the scan moves to a Bulk API 2.0 job. · default 10000
fields := VARCHAR[]
Field API names or parent relationship paths to return, such as Account.Name; NULL returns every field. Columns are named by the mangling rule (see meta.columns). · default null
include_deleted := BOOLEAN
Include soft-deleted and archived rows (queryAll / Bulk queryAll). · default false
max_rows := BIGINT
Optional SOQL LIMIT. · default null
modified_after := TIMESTAMP WITH TIME ZONE
Only rows with SystemModstamp >= this instant (incremental extracts). · default null
modified_before := TIMESTAMP WITH TIME ZONE
Only rows with SystemModstamp < this instant. · default null
order_by := VARCHAR
Optional SOQL ORDER BY text, e.g. 'CloseDate DESC'. Disables locator-expiry resume (which needs SystemModstamp order). · default null
resume := BOOLEAN
Continue an unfinished journalled scan of the same query from its saved Bulk job + locator. · default false
where_clause := VARCHAR
Optional raw SOQL condition ANDed into the WHERE clause, e.g. 'IsWon = TRUE'. · default null
Returns columns
id VARCHAR
The record id (18 characters).
stage_name VARCHAR
StageName (picklist).
amount DECIMAL(16,2)
Amount (currency, precision and scale from describe).
close_date DATE
CloseDate.
is_won BOOLEAN
IsWon.
system_modstamp TIMESTAMP WITH TIME ZONE
Last system change, the incremental watermark.
stage_name VARCHAR
A plain field, typed from describe.
account_owner_name VARCHAR
A parent relationship path, flattened with underscores.
expr0 BIGINT
An unaliased aggregate, numbered as the API numbers it.
total DOUBLE
An aliased SUM/AVG (MIN/MAX keep the field's type).
Returns columns · depends on the arguments
Object scan (query_object, sobjects views, lookup)
id VARCHAR
The record id (18 characters).
stage_name VARCHAR
StageName (picklist).
amount DECIMAL(16,2)
Amount (currency, precision and scale from describe).
close_date DATE
CloseDate.
is_won BOOLEAN
IsWon.
system_modstamp TIMESTAMP WITH TIME ZONE
Last system change, the incremental watermark.
SOQL query (soql)
stage_name VARCHAR
A plain field, typed from describe.
account_owner_name VARCHAR
A parent relationship path, flattened with underscores.
expr0 BIGINT
An unaliased aggregate, numbered as the API numbers it.
total DOUBLE
An aliased SUM/AVG (MIN/MAX keep the field's type).
Examples (2)

Open pipeline by stage (only StageName and Amount are fetched)

SELECT stage_name, count(*) AS deals, sum(amount) AS pipeline
FROM salesforce.main.query_object('Opportunity', fields := ['StageName', 'Amount'])
WHERE NOT is_closed
GROUP BY stage_name
ORDER BY pipeline DESC;

Incremental extract: accounts changed since a watermark

SELECT id, name, system_modstamp
FROM salesforce.main.query_object('Account', fields := ['Id', 'Name', 'SystemModstamp'], modified_after := TIMESTAMPTZ '2026-01-01 00:00:00+00')
ORDER BY system_modstamp;
Link
record (object_name VARCHAR, sf_id VARCHAR) 1 example

Fetch whole records as JSON by (object, id), batched 200 ids per API call

Arguments
object_name VARCHAR
Object API name of the record, e.g. the result of object_of(what_id).
sf_id VARCHAR
Record id (15 or 18 characters).
Returns columns
object_name VARCHAR
The object API name passed in.
sf_id VARCHAR
The 18-character record id.
doc JSON
Every readable field of the record (NULL when no such record is visible).
Example

Resolve a polymorphic WhatId to its record

SELECT r.doc->>'StageName' AS stage
FROM (VALUES ('006Dn000001aBcD')) t(what_id),
     LATERAL salesforce.main.record(salesforce.main.object_of(t.what_id), t.what_id) r;
Link
soql (query VARCHAR, api := VARCHAR, bulk_page_size := BIGINT, bulk_threshold := BIGINT, include_deleted := BOOLEAN, resume := BOOLEAN) 2 examples

Run a SOQL query; the result is typed at bind time from the select list and the org's describe metadata

Positional arguments
query VARCHAR
A SOQL query. Select items: fields, parent paths (Account.Owner.Name), COUNT(), COUNT/COUNT_DISTINCT/SUM/AVG/MIN/MAX(f), date functions (CALENDAR_YEAR(f) …), GROUPING(f), FIELDS(STANDARD). Anything else is a bind error.
Named arguments
api := VARCHAR
'auto' (REST, switching to Bulk API 2.0 above bulk_threshold rows), 'rest' or 'bulk'. Aggregates are REST-only. · default "auto"
bulk_page_size := BIGINT
Records per Bulk API 2.0 results page (maxRecords); each page is one Sforce-Locator step. · default 50000
bulk_threshold := BIGINT
In api 'auto', the totalSize above which the scan moves to a Bulk API 2.0 job. · default 10000
include_deleted := BOOLEAN
Include soft-deleted and archived rows (queryAll). · default false
resume := BOOLEAN
Continue an unfinished journalled scan of the same query from its saved Bulk job + locator. · default false
Returns columns
id VARCHAR
The record id (18 characters).
stage_name VARCHAR
StageName (picklist).
amount DECIMAL(16,2)
Amount (currency, precision and scale from describe).
close_date DATE
CloseDate.
is_won BOOLEAN
IsWon.
system_modstamp TIMESTAMP WITH TIME ZONE
Last system change, the incremental watermark.
stage_name VARCHAR
A plain field, typed from describe.
account_owner_name VARCHAR
A parent relationship path, flattened with underscores.
expr0 BIGINT
An unaliased aggregate, numbered as the API numbers it.
total DOUBLE
An aliased SUM/AVG (MIN/MAX keep the field's type).
Returns columns · depends on the arguments
Object scan (query_object, sobjects views, lookup)
id VARCHAR
The record id (18 characters).
stage_name VARCHAR
StageName (picklist).
amount DECIMAL(16,2)
Amount (currency, precision and scale from describe).
close_date DATE
CloseDate.
is_won BOOLEAN
IsWon.
system_modstamp TIMESTAMP WITH TIME ZONE
Last system change, the incremental watermark.
SOQL query (soql)
stage_name VARCHAR
A plain field, typed from describe.
account_owner_name VARCHAR
A parent relationship path, flattened with underscores.
expr0 BIGINT
An unaliased aggregate, numbered as the API numbers it.
total DOUBLE
An aliased SUM/AVG (MIN/MAX keep the field's type).
Examples (2)

Pipeline by stage, aggregated by Salesforce

SELECT stage_name, deals, total
FROM salesforce.main.soql('SELECT StageName, COUNT(Id) deals, SUM(Amount) total FROM Opportunity GROUP BY StageName')
WHERE deals > 1
ORDER BY total DESC;

Contacts with their account and the account owner (relationship paths flatten to columns)

SELECT name, account_name, account_owner_name
FROM salesforce.main.soql('SELECT Name, Account.Name, Account.Owner.Name FROM Contact WHERE Email != null')
ORDER BY name;
Link
updated_ids (object_name VARCHAR, start_date TIMESTAMP WITH TIME ZONE, end_date TIMESTAMP WITH TIME ZONE) 1 example

Ids of records of an object created or updated in a time window (REST getUpdated)

Arguments
object_name VARCHAR
Object API name (must be replicateable, see meta.objects).
start_date TIMESTAMP WITH TIME ZONE
Window start (inclusive). Longer than 30 days is split automatically.
end_date TIMESTAMP WITH TIME ZONE
Window end.
Returns columns
sf_id VARCHAR
Record id (18 characters).
latest_date_covered TIMESTAMP WITH TIME ZONE
The window end Salesforce guarantees complete.
Example

How many opportunities changed in the last day

SELECT count(*) AS changed
FROM salesforce.main.updated_ids('Opportunity', now() - INTERVAL 1 DAY, now());
Link
meta 10 tables

Org metadata and operations: describe information, users and access, API limits and Bulk API 2.0 jobs.

Schema examples (10)
Examples (10)

Custom objects you can query

SELECT name, label, key_prefix
FROM salesforce.meta.objects
WHERE custom AND queryable
ORDER BY name;

Daily limits, most used first

SELECT limit_name, maximum, remaining, round(used_pct, 1) AS used_pct
FROM salesforce.meta.limits
WHERE limit_name LIKE 'Daily%'
ORDER BY used_pct DESC;

Bulk jobs this worker ran, newest first

SELECT id, object_name, state, records_read, journal_state
FROM salesforce.meta.jobs
WHERE journal_state IS NOT NULL
ORDER BY created_date DESC;

Record types by object

SELECT object_name, developer_name, active
FROM salesforce.meta.record_types
ORDER BY object_name, developer_name;
6 more examples

What the custom fields of Account are called in SQL

SELECT sf_field_name, column_name, duckdb_type
FROM salesforce.meta.columns
WHERE object_name = 'Account' AND sf_field_name LIKE '%__c'
ORDER BY column_name;

Active opportunity stages

SELECT value, label
FROM salesforce.meta.picklist_values
WHERE object_name = 'Opportunity' AND field_name = 'StageName' AND active
ORDER BY value;

Active users per profile

SELECT profile_name, count(*) AS users
FROM salesforce.meta.users
WHERE active
GROUP BY profile_name
ORDER BY users DESC;

Profiles in use

SELECT name, user_license, active_users
FROM salesforce.meta.profiles
WHERE active_users > 0
ORDER BY active_users DESC;

Most-assigned permission sets

SELECT label, assignments
FROM salesforce.meta.permission_sets
ORDER BY assignments DESC, label
LIMIT 10;

Which org am I connected to?

SELECT org_id, name, edition, is_sandbox, api_version
FROM salesforce.meta.organizations;
Tables
columns 1 example10 cols

The column-name mapping of every object in the ATTACH OBJECTS list: Salesforce field → DuckDB column and type

Columns
object_namenot null VARCHAR
Object API name.
sf_field_namenot null VARCHAR
Salesforce field API name.
column_name VARCHAR
DuckDB column name.
duckdb_type VARCHAR
DuckDB column type.
sf_type VARCHAR
Salesforce field type.
label VARCHAR
Field label.
filterable BOOLEAN
SQL filters on this column are pushed into SOQL WHERE.
nillable BOOLEAN
The field can be empty.
custom BOOLEAN
Custom field (__c).
is_relationship_path BOOLEAN
The column is a parent relationship path (never for object views).
ConstraintsPRIMARY KEY (object_name, sf_field_name)
Example

What the custom fields of Account are called in SQL

SELECT sf_field_name, column_name, duckdb_type
FROM salesforce.meta.columns
WHERE object_name = 'Account' AND sf_field_name LIKE '%__c'
ORDER BY column_name;
Link
jobs 1 example12 cols

Bulk API 2.0 query jobs in the org joined with this worker's scan journal (locator, records read)

Columns
idnot null VARCHAR
Bulk job id (750…).
object_name VARCHAR
Object queried.
operation VARCHAR
query or queryAll.
state VARCHAR
UploadComplete, InProgress, JobComplete, Failed or Aborted.
created_date TIMESTAMP WITH TIME ZONE
When the job was created.
api_version VARCHAR
API version the job was created with (results must be read with the same one).
locator VARCHAR
Journalled Sforce-Locator of the next unread page (null when complete or not ours).
records_read BIGINT
Count of records this worker has read from the job so far.
query_sha256 VARCHAR
Hash of instance, API version and SOQL that keys the journal.
resumable BOOLEAN
Whether an expired job can be recovered by SystemModstamp.
journal_state VARCHAR
running, complete or failed (null when the job was not run by this worker).
error_message VARCHAR
Failure message, from the job or the journal.
ConstraintsPRIMARY KEY (id)
Example

Bulk jobs this worker ran, newest first

SELECT id, object_name, state, records_read, journal_state
FROM salesforce.meta.jobs
WHERE journal_state IS NOT NULL
ORDER BY created_date DESC;
Link
limits 1 example5 cols

The org's API limits (/limits): maximum and remaining per limit, plus the worker's quota-guard view

Columns
limit_namenot null VARCHAR
Limit name, e.g. DailyApiRequests.
maximum BIGINT
The limit's allowance, in the limit's own unit (requests, jobs or MB).
remaining BIGINT
Allowance left, in the limit's unit (requests, jobs or MB).
used BIGINT
Allowance consumed (maximum minus remaining), in the limit's unit.
used_pct DOUBLE
Percentage of the limit used (0-100).
ConstraintsPRIMARY KEY (limit_name)
Example

Daily limits, most used first

SELECT limit_name, maximum, remaining, round(used_pct, 1) AS used_pct
FROM salesforce.meta.limits
WHERE limit_name LIKE 'Daily%'
ORDER BY used_pct DESC;
Link
objects 1 example13 cols

Every object in the org (describeGlobal): name, label, key prefix and capabilities

Columns
namenot null VARCHAR
Object API name, e.g. Account or Invoice__c.
label VARCHAR
Singular label.
label_plural VARCHAR
Plural label.
key_prefix VARCHAR
3-character record id prefix (null for objects without records).
custom BOOLEAN
True for custom objects (__c).
queryable BOOLEAN
Can be read with SOQL.
createable BOOLEAN
Records can be created.
updateable BOOLEAN
Records can be updated.
deletable BOOLEAN
Records can be deleted.
replicateable BOOLEAN
Supports getUpdated / getDeleted (updated_ids / deleted_ids).
retrieveable BOOLEAN
Records can be retrieved by id.
searchable BOOLEAN
Included in SOSL search.
custom_setting BOOLEAN
True for custom settings.
ConstraintsPRIMARY KEY (name)
Example

Custom objects you can query

SELECT name, label, key_prefix
FROM salesforce.meta.objects
WHERE custom AND queryable
ORDER BY name;
Link
organizations 1 example12 cols

The connected org: id, name, edition, instance, sandbox flag, locale, and the API version in use

Columns
org_idnot null VARCHAR
Organization id (00D…).
name VARCHAR
Org name.
edition VARCHAR
Edition (OrganizationType).
instance_name VARCHAR
Pod, e.g. NA224.
is_sandbox BOOLEAN
True for sandboxes.
namespace_prefix VARCHAR
Org namespace (developer orgs).
default_locale VARCHAR
DefaultLocaleSidKey.
time_zone VARCHAR
TimeZoneSidKey.
language VARCHAR
LanguageLocaleKey.
created_date TIMESTAMP WITH TIME ZONE
When the org was created.
instance_url VARCHAR
Instance URL from the salesforce secret.
api_version VARCHAR
REST API version in use.
ConstraintsPRIMARY KEY (org_id)
Example

Which org am I connected to?

SELECT org_id, name, edition, is_sandbox, api_version
FROM salesforce.meta.organizations;
Link
permission_sets 1 example6 cols

Permission sets (not owned by profiles) with their assignment counts

Columns
idnot null VARCHAR
Permission set id (0PS…).
name VARCHAR
API name.
label VARCHAR
Display name shown in Setup.
custom BOOLEAN
Custom (not standard) permission set.
description VARCHAR
Admin-entered explanation of the access it grants.
assignments BIGINT
Count of users the permission set is assigned to.
ConstraintsPRIMARY KEY (id)
Example

Most-assigned permission sets

SELECT label, assignments
FROM salesforce.meta.permission_sets
ORDER BY assignments DESC, label
LIMIT 10;
Link
picklist_values 1 example6 cols

Picklist and multi-select picklist values of every object in the ATTACH OBJECTS list

Columns
object_namenot null VARCHAR
Object API name.
field_namenot null VARCHAR
Field API name.
valuenot null VARCHAR
API value.
label VARCHAR
Display label.
active BOOLEAN
Whether the value can be chosen.
default_value BOOLEAN
Whether it is the field's default.
ConstraintsPRIMARY KEY (object_name, field_name, value)
Example

Active opportunity stages

SELECT value, label
FROM salesforce.meta.picklist_values
WHERE object_name = 'Opportunity' AND field_name = 'StageName' AND active
ORDER BY value;
Link
profiles 1 example6 cols

Profiles with their license and how many active users hold each

Columns
idnot null VARCHAR
Profile id (00e…).
name VARCHAR
Profile name.
user_license VARCHAR
User license name.
user_type VARCHAR
License category the profile applies to (Standard, PowerPartner, …).
description VARCHAR
Admin-entered explanation of the profile's purpose.
active_users BIGINT
Count of active users assigned this profile.
ConstraintsPRIMARY KEY (id)
Example

Profiles in use

SELECT name, user_license, active_users
FROM salesforce.meta.profiles
WHERE active_users > 0
ORDER BY active_users DESC;
Link
record_types 1 example6 cols

Record types of every object (one SOQL query on RecordType)

Columns
object_name VARCHAR
Object the record type belongs to.
idnot null VARCHAR
Record type id (012…); objects carry it in their record_type_id column.
developer_name VARCHAR
API name.
name VARCHAR
Label.
description VARCHAR
Admin-entered explanation of what the record type is for.
active BOOLEAN
Whether the record type is active.
ConstraintsPRIMARY KEY (id)
Example

Record types by object

SELECT object_name, developer_name, active
FROM salesforce.meta.record_types
ORDER BY object_name, developer_name;
Link
users 1 example12 cols

Users of the org with profile and role names

Columns
idnot null VARCHAR
User id (005…); joins owner_id / created_by_id columns.
username VARCHAR
Login username.
name VARCHAR
Full name.
email VARCHAR
Email address.
active BOOLEAN
IsActive.
user_type VARCHAR
License category (Standard, PowerPartner, CsnOnly …).
profile_id VARCHAR
Id (00e…) of the profile that sets the user's base permissions; joins meta.profiles.
profile_name VARCHAR
Name of that profile, e.g. System Administrator.
role_id VARCHAR
Id (00E…) of the user's position in the role hierarchy (record sharing); NULL when unassigned.
role_name VARCHAR
Name of that role, e.g. Sales Rep.
last_login TIMESTAMP WITH TIME ZONE
Last successful login.
created_date TIMESTAMP WITH TIME ZONE
When the user was created.
ConstraintsPRIMARY KEY (id) · FOREIGN KEY (profile_id) REFERENCES profiles(id)
Example

Active users per profile

SELECT profile_name, count(*) AS users
FROM salesforce.meta.users
WHERE active
GROUP BY profile_name
ORDER BY users DESC;
Link

Credentials

The secret type salesforce declares, as reported by the worker itself.

salesforce

How to get these credentials

Salesforce org (instance_url) plus OAuth: JWT bearer (client_id + username + private_key), client credentials (client_id + client_secret), refresh token, or a pre-issued access_token. Username/password is not supported.

secret.sql
CREATE SECRET salesforce (
    TYPE salesforce,
    instance_url  '<instance_url>',
    login_url     '<login_url>',
    api_version   '<api_version>',
    client_id     '<client_id>',
    username      '<username>',
    private_key   '<PRIVATE_KEY>',  -- secret
    client_secret '<SALESFORCE_CLIENT_SECRET>',  -- secret
    refresh_token '<REFRESH_TOKEN>',  -- secret
    access_token  '<ACCESS_TOKEN>'  -- secret
);
Key Type Required Description
instance_url VARCHAR — The org's My Domain URL, e.g. https://acme.my.salesforce.com (http:// only for 127.0.0.1/localhost).
login_url VARCHAR — OAuth host for JWT bearer / refresh token: https://login.salesforce.com (default) or https://test.salesforce.com for sandboxes.
api_version VARCHAR — REST API version to pin, e.g. '64.0' (the default).
client_id VARCHAR — Connected app consumer key.
username VARCHAR — JWT bearer: the Salesforce username to act as (the integration user).
private_key secret VARCHAR — JWT bearer: the connected app certificate's RSA private key (PEM).
client_secret secret VARCHAR — Client credentials (or refresh token) flow: the consumer secret.
refresh_token secret VARCHAR — Refresh token flow: an OAuth refresh token for the connected app.
access_token secret VARCHAR — A pre-issued session/access token (not refreshed; for quick tests).

The worker doesn't mark which keys are required.

Needed by soqlquery_objectdescribe_fieldsupdated_idsdeleted_idsrecordlookuppicklist_values

Create the secret in the same session, after attaching salesforce — the worker registers its secret types at ATTACH. Keys marked secret are masked in duckdb_secrets(); angle-bracket values are placeholders. Read credentials from your environment or secret store in your application and pass them through your SQL client’s parameter bindings. Keep real values out of saved SQL and history. Native DuckDB and Haybarn do not provide a SQL getenv() function.

Try these queries

15- and 18-character forms of the same id collapse to one join key

SELECT salesforce.main.id18(opportunity_id) AS join_key, count(*) AS rows
FROM (VALUES ('001Dn00000AbCdE'), ('001Dn00000AbCdEIAV')) t(opportunity_id)
GROUP BY join_key

Uses id18

Shorten an API id to its report form

SELECT salesforce.main.id15('001Dn00000AbCdEIAV') AS short_id

Uses id15

Count ids by object-type prefix

SELECT salesforce.main.key_prefix(what_id) AS prefix, count(*) AS tasks
FROM (VALUES ('006Dn000001aBcD'), ('001Dn00000AbCdE')) t(what_id)
GROUP BY prefix
ORDER BY prefix

Uses key_prefix

Resolve polymorphic WhatIds to object names

SELECT salesforce.main.object_of(what_id) AS target, count(*) AS tasks
FROM (VALUES ('006Dn000001aBcD'), ('500Dn000002XyZq'), ('006Dn000003aBcE')) t(what_id)
GROUP BY target
ORDER BY target

Uses object_of

Count valid and invalid ids in an export

SELECT count(*) FILTER (WHERE salesforce.main.is_valid_id(id)) AS valid,
  count(*) FILTER (WHERE NOT salesforce.main.is_valid_id(id)) AS invalid
FROM (VALUES ('001Dn00000AbCdEIAV'), ('001Dn00000AbCdEAAA'), ('n/a')) t(id)

Uses is_valid_id

Build a WHERE clause from a value with a quote in it

SELECT 'LastName = ' || salesforce.main.soql_literal(last_name) AS where_clause
FROM (VALUES ('O''Brien')) t(last_name)

Uses soql_literal

27 more examples in the Catalog, each listed under the table or function it uses.

Questions it can answer

Plain-English questions from the worker's agent test tasks. An AI agent with this catalog attached should answer each one with SQL.

  • Using the salesforce worker, convert the 15-character Salesforce id 001Dn00000AbCdE to its 18-character case-safe form.
  • Using the salesforce worker, which standard Salesforce object does the id 00QDn000001aBcD belong to, and what is its key prefix and 15-character form?
  • What is the total open (not closed) opportunity amount per stage in the connected Salesforce org?
  • Using SOQL through the salesforce worker, count the won opportunities and their total amount.
  • For each Salesforce task whose WhatId is an opportunity, list the task subject with the opportunity's name, and also give the raw record JSON's StageName.
  • List the picklist values of the Opportunity StageName field, both from the per-field function and from the attached objects' metadata table.

Salesforce is an independent open-source connector from Query.Farm. It is not affiliated with, endorsed by or sponsored by the services, projects or organisations it works with. Product names, logos and trademarks belong to their respective owners.