New to Claude Skills? Learn how to install them →

forcedotcom on GitHub

SOQL Query Expert

OfficialFree

Optimize and generate Salesforce SOQL queries effortlessly.

by forcedotcom808 stars on forcedotcom/sf-skills
1 views
Updated Aug 10, 2026
Get this skill

Free · Opens the source repo

What SOQL Query Expert does

The platform-soql-query skill is designed for developers and administrators working with Salesforce who need to create, optimize, and analyze SOQL (Salesforce Object Query Language) and SOSL (Salesforce Object Search Language) queries. This skill provides a comprehensive toolkit for generating queries from natural language input, handling complex relationships, and performing aggregate queries, all while ensuring that the queries adhere to Salesforce's performance and safety best practices.

When using this skill, users can generate queries that are not only syntactically correct but also optimized for performance. It assists in drafting queries by providing schema-aware completions, helping users avoid common pitfalls such as incorrect object or field names. The skill also includes tools for validating queries against the target Salesforce org, ensuring that every identifier is accurate before execution. This is crucial for maintaining the integrity and efficiency of database operations within Salesforce.

The skill is particularly useful in scenarios where users are dealing with .soql files, need to analyze existing queries for performance improvements, or require assistance in understanding complex relationship queries. It also provides a scoring mechanism that evaluates query performance, allowing users to make informed decisions about query structure and execution. This makes it an essential resource for anyone looking to enhance their Salesforce query capabilities.

However, it is important to note that this skill is not intended for bulk data operations or for embedding query logic within Apex classes. For those tasks, users should refer to other skills designed specifically for data management or Apex code generation. Overall, platform-soql-query is a valuable tool for Salesforce developers seeking to streamline their query development process and improve the performance of their database interactions.

When to use it

Use this skill when you need to author or optimize SOQL/SOSL queries, particularly when working with `.soql` files or complex relationships.

When not to use it

Avoid this skill for bulk data operations or when embedding queries in Apex logic, where other specialized tools are more appropriate.

What you can build with it

Generating a Complex Query

You need to create a SOQL query that retrieves related records across multiple objects. This skill will help you draft the query accurately.

Optimizing Existing Queries

You have a set of existing SOQL queries that are performing poorly. Use this skill to analyze and optimize them for better performance.

Validating Queries Before Execution

Before running a query in production, you want to ensure it is valid and efficient. This skill will validate the query against the Salesforce schema.

How to install SOQL Query Expert

View source

1. Install with the skills CLI

npx skills add forcedotcom/sf-skills/platform-soql-query --agent claude-code

2. Or install it manually

Download the skill folder and drop it into ~/.claude/skills/ for all projects, or .claude/skills/ to scope it to one repo. Restart Claude Code so it picks up the new skill.

Anthropic's agentic coding CLI, and the reference implementation of Agent Skills. Drop a skill folder into ~/.claude/skills and Claude Code loads it automatically whenever a task matches the skill's description. Claude Code docs

Inside SKILL.md

Written by forcedotcom

platform-soql-query: Salesforce SOQL Query Expert

Use this skill when the user needs SOQL/SOSL authoring or optimization: natural-language-to-query generation, relationship queries, aggregates, query-plan analysis, and performance/safety improvements for Salesforce queries.

When This Skill Owns the Task

Use platform-soql-query when the work involves:

  • .soql files
  • query generation from natural language
  • relationship queries and aggregate queries
  • query optimization and selectivity analysis
  • SOQL/SOSL syntax and governor-aware design

Delegate elsewhere when the user is:


Required Context to Gather First

Ask for or infer:

  • target object(s)
  • fields needed
  • filter criteria
  • sort / limit requirements
  • whether the query is for display, automation, reporting-like analysis, or Apex usage
  • whether performance / selectivity is already a concern

Recommended Workflow

1. Generate the simplest correct query

Prefer:

  • only needed fields
  • clear WHERE criteria
  • reasonable LIMIT when appropriate
  • relationship depth only as deep as necessary

While drafting, call mcp__plugin_salesforce-development_salesforce-lsp__complete_soql with the partial query to get schema-aware completion of object, field, and relationship names against the connected org — this avoids guessing API names that then fail validation. On error envelope or unavailable ({error: <code>} / tool not registered), skip completion and rely on the syntax reference in references/soql-syntax-reference.md.

When the query already lives inside an Apex class (optimizing or debugging embedded SOQL rather than authoring new), call mcp__plugin_salesforce-development_salesforce-lsp__extract_soql_from_apex with the .cls file to pull the SOQL strings out before analyzing them, so you optimize the exact query the class runs.

2. Choose the right query shape

NeedDefault pattern
parent data from childchild-to-parent traversal
child rows from parentsubquery
counts / rollupsaggregate query
records with / without related rowssemi-join / anti-join
text search across objectsSOSL

3. Validate with LSP tools (REQUIRED)

REQUIRED: Before running a SOQL query against the org or recommending it for production use:

  1. Call mcp__plugin_salesforce-development_salesforce-lsp__validate_soql with the query string to check syntax and catch parse errors before execution.

    • On success ({ok: true}), proceed. A clean parse is not a clean query. validate_soql is parser-only — it accepts objects, fields, and relationships that do not exist in the target org. A successful parse means the syntax is well-formed, NOT that the identifiers resolve.
    • Fail closed on an uncertain result. If the call timed out, was retried, or its result is otherwise uncertain, do NOT treat it as a successful validation — fall back to step 2 and record validate_soql=unavailable: timeout.
    • On error envelope ({error: <code>}), record validate_soql=unavailable: <code> and fall back to step 2.
    • On unavailable (tool not registered), record validate_soql=unavailable: lsp_not_present and fall back to step 2.
  2. Verify identifiers against org schema (REQUIRED, even when the parse succeeds). Confirm every object, field, and relationship in the query actually exists in the target org before recommending it — a well-formed parse over a nonexistent field must not be reported as valid.

    • Authoritative check — describe or a bounded probe. Do NOT execute the user's full query to verify schema (it may be unbounded and retrieve large result sets). Instead:
      • Preferred: sf sobject describe --sobject <Object> --target-org <org> for each object in the query, and confirm every referenced field/relationship appears in the describe output. This resolves identifiers with no rows retrieved.
      • Alternative: a bounded org-backed probe — the same query rewritten with LIMIT 0 (or the object's key with LIMIT 1) via sf data query --query "<bounded-query>" --json --target-org <org>. LIMIT 0 validates every identifier server-side while returning no rows; a bad object or field surfaces as an INVALID_TYPE / INVALID_FIELD error.
    • mcp__plugin_salesforce-development_salesforce-lsp__complete_soql may be used to resolve names while drafting, but completion returns candidates at a cursor position — not a validation result for every identifier — and can return {ok: true, hint: "no_org_connected"} with placeholder schema. Completion output is NOT sufficient schema verification: if complete_soql returns no_org_connected or does not resolve every identifier, fall back to the describe or bounded-probe check above.
    • NEVER report a query as valid because the validation check didn't run or only parsed — always confirm identifiers against the org schema first.
  3. For production queries, also call mcp__plugin_salesforce-development_salesforce-lsp__check_soql_selectivity to analyze selectivity heuristics before recommending the query for high-volume or scheduled use.

    • On error envelope or unavailable, record check_soql_selectivity=unavailable: <code> and note selectivity was not verified.
  4. After deploying schema changes, if a field or object reference fails validation immediately after deployment, call mcp__plugin_salesforce-development_salesforce-lsp__refresh_org_schema to invalidate the cached org describe, then re-validate before assuming a code error.

See the platform-lsp-integrate skill for the complete LSP Call/Fallback Contract and error code reference.

4. Optimize for selectivity and safety

Check:

  • indexed / selective filters
  • no unnecessary fields
  • no avoidable wildcard or scan-heavy patterns
  • security enforcement expectations

5. Validate execution path if needed

If the user wants runtime verification, hand off execution to:


High-Signal Rules

  • never use SELECT * style thinking; query only required fields
  • do not query inside loops in Apex contexts
  • prefer filtering in SOQL rather than post-filtering in Apex
  • use aggregates for counts and grouped summaries instead of loading unnecessary records
  • evaluate wildcard usage carefully; leading wildcards often defeat indexes
  • account for security mode / field access requirements when queries move into Apex

Output Format

When finishing, report in this order:

  1. Query purpose
  2. Final SOQL/SOSL
  3. Why this shape was chosen
  4. Optimization or security notes
  5. Execution suggestion if needed

Suggested shape — use references/soql-syntax-reference.md for exact syntax:

Query goal: <summary>
Query: <soql or sosl>
Design: <relationship / aggregate / filter choices>
Notes: <selectivity, limits, security, governor awareness>
Next step: <run in platform-data-manage or embed in Apex>

Cross-Skill Integration

NeedDelegate toReason
run the query against an orgplatform-data-manageexecution and export
embed the query in services/selectorsplatform-apex-generateimplementation context
analyze slow-query symptoms from logsplatform-apex-logs-debugruntime evidence
wire query-backed UIexperience-lwc-generatefrontend integration

Score Guide

ScoreMeaning
90+production-optimized query
80–89good query with minor improvements possible
70–79functional but performance concerns remain
< 70needs revision before production use

Reference File Index

FileWhen to read
references/soql-syntax-reference.mdSyntax, operators, date literals, relationship query patterns
references/query-optimization.mdSelectivity rules, indexing strategy, governor limits, security patterns
references/soql-reference.mdQuick reference — operators, date functions, aggregate functions, WITH clauses
references/anti-patterns.mdCommon SOQL mistakes and their fixes — read before finalizing any query
references/selector-patterns.mdApex selector layer patterns — read when embedding queries in Apex classes
references/field-coverage-rules.mdField coverage validation — read when generating SOQL used inside Apex code
references/cli-commands.mdsf CLI query execution, bulk export, query plan commands
assets/basic-queries.soqlStarter query examples for common objects
assets/relationship-queries.soqlParent-to-child and child-to-parent relationship query patterns
assets/aggregate-queries.soqlCOUNT, SUM, GROUP BY, ROLLUP query patterns
assets/optimization-patterns.soqlSelective filter and index-aware query patterns
assets/bulkified-query-pattern.clsApex Map-based bulk query pattern for trigger contexts
assets/selector-class.clsFull selector class implementation template
scripts/post-tool-validate.pyPost-write hook — runs static SOQL validation and live query plan analysis after .soql file edits

Frequently asked questions about SOQL Query Expert

Similar skills