grzmol/vibe-force/sf-soql-sosl-optimization
Claude Code and agent skill by grzmol/vibe-force
- community
Checking that the SKILL.md file is still in the repository.
Diagnoses and rewrites slow or non-selective SOQL and SOSL on Salesforce, covering the Lightning Platform query optimizer, standard and custom index selectivity thresholds, skinny tables, two-column indexes, external IDs, the Query Plan and REST explain tools, SOQL_EXECUTE log analysis, relationship query depth limits, aggregate queries with GROUP BY ROLLUP and CUBE, FOR UPDATE row locks, LIMIT and OFFSET caps, SOQL for loops, query locators and Apex cursors, injection-safe dynamic SOQL with Database.queryWithBinds, SOSL search semantics, and large-data-volume strategies such as PK chunking and Bulk API 2.0 query. Use this skill when a query times out or throws QUERY_TIMEOUT, OPERATION_TOO_LARGE, NUMBER_OUTSIDE_VALID_RANGE, QUERY_TOO_COMPLICATED, or "Aggregate query has too many rows for direct assignment", when a trigger or batch start method must be made selective, when planning an index or skinny table, or when choosing between SOQL, SOSL, and Bulk API for a large read.
Install
npx vskill@latest install grzmol/vibe-force/sf-soql-sosl-optimizationSKILL.md
The same SKILL.md was published earlier as grzmol/vibe-force/sf-soql-sosl-optimization.
SOQL and SOSL Optimization
When to use
Use this skill whenever a read is the problem: a query that times out, a batch start method that fails to launch, a list view or report that hangs, an unindexed WHERE clause on a multi-million-row object, or a decision between SOQL, SOSL, and the Bulk API. It also owns safe dynamic SOQL construction.
Related skills: sf-governor-limits (full per-transaction limit tables), sf-async-apex-patterns (query locators, cursors, batch chunking), sf-security-model (WITH USER_MODE, AccessLevel, stripInaccessible, sharing), sf-data-management (Bulk API 2.0 loads and extracts, data seeding), sf-debugging-logs (capturing and reading SOQL_EXECUTE_* log lines), sf-apex-development (where queries belong in a trigger handler).
Selectivity quick reference
The Lightning Platform query optimizer picks the driving index and join order. It consults an internal statistics table with a pre-query before deciding whether an index helps.
| Index kind | Used when the filter matches | Worked example | |
|---|---|---|---|
| Standard indexed field | < 30% of the first million records and < 15% of each additional million | 2M-row table: 450,000 rows or fewer. 5M-row table: 900,000 rows or fewer | |
| Custom indexed field | < 10% of the first million records and < 5% of each additional million | 500K-row table: 50,000 rows or fewer. 5M-row table: 300,000 rows or fewer | |
AND of several filters | indexes are used unless one of them returns more than 20% of the object's records | also selective if each filter is under twice its own threshold, or the intersection is under the single threshold | |
OR of several filters | indexes are used unless all of them return more than 10% of the object's records; every field in the OR must be indexed for any index to be used | each filter must clear the threshold individually | |
LIKE | the optimizer samples up to 100,000 actual records instead of using the statistics table | ||
CONTAINS | a custom index is typically not used once the scan exceeds 333,333 rows, because CONTAINS requires a full index scan | threshold subject to change |
Apex Developer Guide rule of thumb: a query is selective when a filter on an indexed field matches less than 10% of total rows.
Indexed by default on most objects: Id (primary key), Name, OwnerId, CreatedDate, SystemModstamp / LastModifiedDate, RecordTypeId, Division, Email on Contact and Lead, every lookup and master-detail foreign key, and every custom field marked External ID or Unique. Salesforce also auto-indexes fields when the optimizer sees that an index would help frequently run queries.
Cannot be custom-indexed: text area (long), text area (rich), non-deterministic formula fields, encrypted text, multi-select picklists, currency fields in a multi-currency org, binary fields (blob, file), and formula fields that call TEXT() on a picklist.
Core patterns
1. Measure selectivity before you tune
GROUP BY ROLLUP returns the per-value counts and the grand total, which is exactly the pair of numbers a selectivity decision needs. IsDeleted exists on every standard and custom object; soft deleted records sit in the Recycle Bin for 15 days and still cost query time.
2. Get the execution plan
The response returns plans[], sorted most to least optimal; the first plan is the one that runs.
| Field | Read it as | |
|---|---|---|
leadingOperationType | Index (uses an index on the query object), Sharing (uses a sharing-rule-based index), Other (internal optimization), TableScan (no index - the thing to fix) | |
relativeCost | cost relative to the selective-query threshold. Greater than 1.0 means non-selective | |
cardinality | estimated rows the query returns | |
sobjectCardinality | approximate total rows for the object in this org | |
fields | the index fields used when leadingOperationType is Index, otherwise null | |
notes[] | description, fields, tableEnumOrId - explains optimizations that could not be used and why |
The Developer Console Query Editor exposes the same data through its Query Plan panel.
3. Read the debug log
| Log event | Category / level | Payload | |
|---|---|---|---|
SOQL_EXECUTE_BEGIN | DB, INFO and above | line number, number of aggregations, query source | |
SOQL_EXECUTE_END | DB, INFO and above | line number, number of rows, duration in milliseconds | |
SOQL_EXECUTE_EXPLAIN | DB, FINEST | Query Plan details for the executed query | |
SOSL_EXECUTE_BEGIN | DB, INFO and above | line number, query source | |
SOSL_EXECUTE_END | DB, INFO and above | line number, number of rows, duration in milliseconds |
SOQL_EXECUTE_EXPLAIN needs the DB category at FINEST, so a default trace flag will not show it. See skill sf-debugging-logs for trace-flag setup.
In-transaction counters:
4. Keep the row set out of the heap
The SOQL for loop uses internal query/queryMore chunking, which avoids the 10 MB (synchronous) or 25 MB (asynchronous) heap limit at the cost of extra CPU. For genuine mass updates prefer Batch Apex or Apex cursors; see skill sf-async-apex-patterns.
5. Injection-safe dynamic SOQL
Database.queryWithBinds (API 57.0 and later) resolves bind variables from a Map instead of from Apex scope. Map-key rules: keys are compared case-insensitively and duplicate case-insensitive keys throw System.QueryException: The bindMap consists of duplicate case-insensitive keys: [...]; keys must start with an ASCII letter, must not start with a number, must not be reserved words, and dot notation is discouraged.
Companion dynamic methods: Database.query, Database.countQuery, Database.countQueryWithBinds, Database.getQueryLocator, Database.getQueryLocatorWithBinds, Database.getCursor, Database.getCursorWithBinds.
When a value must be concatenated rather than bound - an object or field API name, or a sort direction - never interpolate raw user input. Bind what you can, and pass the rest through String.escapeSingleQuotes() after validating it against an allowlist derived from Schema.getGlobalDescribe().
6. Enforce security in the query
From API version 67.0 Apex runs in user context by default, classes without an explicit sharing declaration run as with sharing, and WITH SECURITY_ENFORCED is no longer allowed in Apex SOQL SELECT statements - use WITH USER_MODE. WITH USER_MODE respects FLS, object permissions, and sharing rules; it also has fewer limitations than the old WITH SECURITY_ENFORCED clause, which Salesforce explicitly recommends against. Security.stripInaccessible() remains the tool for scrubbing fields from records that were fetched in system mode. Details in skill sf-security-model.
7. Choose SOQL or SOSL deliberately
| Dimension | SOQL | SOSL | |
|---|---|---|---|
| Executes against | the database | the search indexes | |
| API call | query() | search() | |
| Use when | you know the object and field; you need counts, sorting, relationship traversal, or number/date/checkbox filters | you do not know which object or field holds the value; you want an efficient cross-object text hit | |
| Text matching | LIKE with wildcards, no tokenisation | tokenises words within a field, so John matches Paul and John Company | |
Speed on CONTAINS-style searches | slower | generally faster | |
| Per-transaction limit | 100 queries sync / 200 async, 50,000 rows | 20 queries, 2,000 rows per query |
SOSL result stages: the engine matches up to 2,000 records; a single-object query returns up to 250 records unless a WHERE or ORDER BY clause is present, in which case up to 2,000; a multi-object query returns up to min(2000/n, 250) per object; then user permission filters are applied, so result sets vary per user and over time. Users with View All Data see the unfiltered set.
Anti-patterns
Negative and empty-value operators on large objects. !=, NOT CONTAINS, NOT STARTS WITH, and Name != '' all defeat the index.
Filtering on null for picklists and foreign keys. Index tables exclude null rows by default, so WHERE Contact__c != null forces a scan. Design the data model so null is not a meaningful value: substitute a sentinel such as 'NA' or 'Default' and filter on that. Salesforce Support can build a custom index that includes nulls, but existing indexes must be explicitly enabled and rebuilt.
Running the query at all when the bind is null. Guard in Apex instead.
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/sf-soql-sosl-optimization/SKILL.md
Popularity
- Repository stars
- 3
- 7-day trend score
- 7
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/grzmol/vibe-force/sf-soql-sosl-optimization)