Generates and optimizes SOQL queries for Salesforce. Use when writing SOQL queries, converting natural language to SOQL, optimizing query performance, debugging selective/non-selective queries, or working with relationship queries. Do NOT use for DML operations (use sf-data) or Apex logic beyond queries (use sf-apex).
Convert the request to SOQL:
Check for selectivity:
LIKE '%value'!=, NOT IN) on large datasets# Execute query against org
sf data query --query "SELECT Id, Name FROM Account LIMIT 10" --target-org <alias>
# Check query plan (REST API)
sf data query --query "SELECT Id FROM Account WHERE Name = 'Acme'" --target-org <alias> --use-tooling-api
SELECT Id, Name, Industry, Phone
FROM Account
WHERE Industry = 'Technology'
ORDER BY Name ASC
LIMIT 100
SELECT Id, Name,
(SELECT Id, FirstName, LastName, Email
FROM Contacts
WHERE Email != null
ORDER BY LastName)
FROM Account
WHERE Industry = 'Technology'
SELECT Id, FirstName, LastName,
Account.Name, Account.Industry
FROM Contact
WHERE Account.Industry = 'Technology'
SELECT StageName, COUNT(Id) cnt, SUM(Amount) total
FROM Opportunity
WHERE CloseDate = THIS_FISCAL_YEAR
GROUP BY StageName
HAVING SUM(Amount) > 100000
ORDER BY SUM(Amount) DESC
SELECT Id, Name FROM Account
WHERE Id IN (SELECT AccountId FROM Opportunity WHERE StageName = 'Closed Won')
SELECT Id, Name FROM Account
WHERE Id NOT IN (SELECT AccountId FROM Contact)
| Literal | Meaning |
|---|---|
TODAY | Current day |
YESTERDAY | Previous day |
THIS_WEEK | Current week |
LAST_N_DAYS:30 | Past 30 days |
THIS_FISCAL_YEAR | Current fiscal year |
NEXT_N_MONTHS:3 | Next 3 months |
A query is selective when it returns less than:
| Field Type | Indexed by Default |
|---|---|
| Id | Yes |
| Name | Yes |
| OwnerId | Yes |
| RecordTypeId | Yes |
| CreatedDate | Yes |
| SystemModstamp | Yes |
| Lookup/Master-Detail | Yes |
| External ID fields | Yes |
| Custom fields | No (request custom index) |
| Anti-Pattern | Fix |
|---|---|
SELECT * equivalent (all fields) | Select only needed fields |
LIKE '%value%' (leading wildcard) | Use LIKE 'value%' or SOSL |
| No LIMIT on exploratory queries | Always add LIMIT during development |
| No WHERE clause on large objects | Add selective filter criteria |
!= on non-indexed field | Restructure as positive match |
| Query in Apex for-loop | Move query before loop, use Map |
| ORDER BY non-indexed field on large set | Add custom index or restructure |