Run a SOQL or SOSL Query

It’s often useful to run a CLI command to quickly query a Salesforce object or search for specific terms across many objects. For example, maybe you want to see all the Account records for the energy industry, or search for contact or lead names that begin with the letters JO. Salesforce provides two robust search languages for just these use cases: SOQL and SOSL.

SOQL

Use Salesforce Object Query Language (SOQL) to search a single Salesforce or Tooling API object for specific information. SOQL is similar to the SELECT statement in the widely used Structured Query Language (SQL) but is designed specifically for Salesforce data.

This example shows how to run a simple SOQL query against the Account object in your default org:

1sf data query --query "SELECT ID, Name FROM Account WHERE Industry='Energy'"

If your query is long, you can store it in a file and specify the file name to the --file flag, as shown in this example, which runs against an org with the alias new-scratch-org:

1sf data query --file query.txt --target-org new-scratch-org

If your query returns more than 2,000 records, use the data export bulk command instead.

Tip

Use the --all-rows flag to also return records that have been soft-deleted due to a merge or delete. By default, deleted records aren’t returned. To change the format of the output, such as to comma-separated values (CSV) or JSON, use the --result-format flag.

1sf data query --query "SELECT ID, Name FROM Account WHERE Industry='Energy'" --all-rows --result-format json

To query a Tooling API object, include the --use-tooling-api flag. This example also shows how to use the --output-file to write output to a file in CSV format.

1sf data query --query "SELECT ID, Name FROM ApexClass" --use-tooling-api --result-format csv --output-file query-output.csv

SOSL

Use Salesforce Object Search Language (SOSL) search fields across multiple objects.

This SOSL query searches the contacts and leads in your default org for names that start with Jo:

1sf data search 
2  --query "FIND {Jo*} IN Name FIELDS Returning Contact(Name, Phone), Lead(Name, Phone)"

If your SOSL search query is long, you can store it in a file and specify the filename to the --file flag, as shown in this example, which runs against an org with the alias new-scratch-org:

1sf data search --file query.txt --target-org new-scratch-org

Specify --result-format csv to write a comma-separated value (CSV) file to disk:

1sf data search --file query.txt --result-format csv