Run SOQL with SFDX and Export Results to File
Running SOQL against salesforce orgs is quite easy with SFDX. All you have to do is -
sfdx force:data:soql:query -q "your_soql" -u="user@sfdc.com"
Or, you could save a few of your favourite SOQLs in a scripts
folder in your salesforce project root folder and run them on demand.
- Open root folder in VSCode
- Create new file / select existing file. Type some SOQL (e.g.
SELECT Id, Name FROM Account LIMIT 10
) and select it Ctrl+Shift+P
to open command palette > type insfdx.force.data.soql.query.selection
And.. you are done.
But, what if you want to format the results of the SOQL query to something more sane - like JSON for example. You can do that too.
sfdx force:data:soql:query -q "SELECT Id, Name FROM Account LIMIT 10" -u="user@sfdc.com" --json
Or, see results in CSV.
sfdx force:data:soql:query -q "SELECT Id, Name FROM Account LIMIT 10" -u="user@sfdc.com" -r=csv
While this is cool and all that, you cannot feed in SOQL to the sfdx
command from a file or write to a file with just the sfdx
utility. But, that what the operating system is for.
You can pipe the command to output results in whatever format you want (er, only CSV, JSON, or pretty print to a wierd format).
sfdx force:data:soql:query -q "SELECT Id, Name FROM Account LIMIT 10" -u="user@sfdc.com" -r=csv > results.csv
If you are that guy who believes in separation of concerns and strongly believes that SOQL should not be in files, but should be read from other files, we can do that too.
Just create a bat
file (or a shell script) to -
- read file contents (=SOQL) to a variable
- execute SOQL
- output formatted results to a file
All this with these two lines -
SET /p soql=<my_soql.txt
sfdx force:data:soql:query -q "%soql%" -r=csv -u='user@sfdc.com' > c:\results\result1.csv
The above command runs ok as a batch file in command prompt (not Powershell).
The full list of magical things you can do with SOQL query in SFDX is right in front of you. All you need to do is -
sfdx force:data:soql:query -- help
Or, head over to the docs.