
query-optimization
This skill should be used when the user asks to optimize slow T-SQL queries, fix SQL Server performance regressions, improve SARGability, rewrite joins, prove whether joins can be removed, compare temp-table data types, select rewrite templates, diagnose parameter sniffing, evaluate query hints, inspect statistics/cardinality estimates, reduce spills or memory grants, use Query Store, or interpret plan evidence. PROACTIVELY activate for slow queries, scans vs seeks, implicit conversions, bad joins, tempdb spills, query rewrites, partition predicate safety, and before recommending indexes or hints. Provides: evidence-first workflow, rewrite templates, parameter-sniffing playbook, and gating rules before recommending indexes or hints.
- Installs
- 189
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/josiahsiegel/claude-plugin-marketplace --skill query-optimization- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads query-optimization automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
Query Optimization
Comprehensive guide to T-SQL query optimization for SQL Server and Azure SQL Database. Optimize from verified evidence: schema, data types, indexes, row counts, partitioning, execution plans, and allowed change types.
Mandatory Workflow
1. Schema-First Validation
Before recommending rewrites, indexes, or hints, verify or mark unknown:
- SQL Server version, edition, compatibility level, and Azure SQL tier if applicable.
- Full query/procedure text, parameter values, frequency, and runtime target.
- DDL for tables, views, temp tables, table variables, and TVFs.
- Data types for join, filter, grouping, ordering, and temp-table columns, including length, precision, scale, collation, and nullability.
- Existing indexes, constraints, statistics age, partition function/scheme, and row counts.
- Whether objects are local or linked-server/remote sources.
- Allowed change types: query rewrite, new index, huge-table index change, stats update, staging table, computed column, or no code change.
Use ../_shared/optimization-intake.md and ../_shared/assumption-tracker.md. If key facts are missing, provide conditional guidance plus diagnostics instead of final prescriptions.
2. Identify the Root Bottleneck
Use actual execution plans and STATISTICS IO, TIME when possible. Rank findings by measured impact, not just estimated plan percentage:
- High logical reads or row reads.
- Bad estimate vs actual row gaps.
- Scans caused by non-SARGable predicates or missing access paths.
- Key lookups multiplied by many executions.
- Sort/hash/window spills from poor estimates or missing order.
- Remote queries that fail to push predicates or joins to the linked server.
For detailed .sqlplan inspection, load tsql-master:execution-plan-analysis.
3. Fix SARGability and Type Mismatches
SARGable predicates can use ordered index access. Avoid functions or conversions on indexed columns.
| Non-SARGable | Safer pattern |
|---|---|
WHERE YEAR(OrderDate) = 2026 | WHERE OrderDate >= '20260101' AND OrderDate < '20270101' |
WHERE LEFT(Name, 3) = 'ABC' | WHERE Name LIKE 'ABC%' |
WHERE Amount * 1.1 > 1000 | WHERE Amount > 1000 / 1.1 |
WHERE CONVERT(date, Dt) = @d | WHERE Dt >= @d AND Dt < DATEADD(day, 1, @d) |
WHERE VarcharCol = 123 | WHERE VarcharCol = '123' |
Check actual data types. A syntactically SARGable predicate can still scan if a parameter, temp column, or join key has the wrong type or collation.
4. Prove Join Changes
Never remove or replace joins only because selected columns come from one table. Prove:
- Does the join filter rows? Compare base count vs joined count and check trusted foreign keys.
- Does the join multiply rows? Check uniqueness on the joined key and duplicates in the referenced table.
- Can it be replaced with
EXISTS? Use a semi-join when only existence is needed and row multiplication must be avoided. - Are outer joins preserved? Predicates in
WHEREcan accidentally convertLEFT JOINto inner join.
Move join-removal experiments into a proof harness and validate equivalence with EXCEPT in both directions. See references/rewrite-proof-harnesses.md.
5. Check Temp Tables and Staging Types
Temp tables are often the right optimization tool, but bad types can create hidden conversions.
Before using or recommending a temp table:
- Compare staged column types against source metadata.
- Match string length and collation for join/filter columns.
- Match numeric precision/scale and date/time precision.
- Add appropriate clustered or nonclustered indexes after load when row counts justify them.
- Update temp-table statistics when phased optimization depends on accurate cardinality.
Flag mismatches as first-order findings because they can invalidate plan analysis and index recommendations. Use the checker in references/rewrite-proof-harnesses.md.
6. Select the Rewrite Template
Choose the least invasive rewrite that addresses the verified bottleneck:
| Situation | Template |
|---|---|
| Highly selective predicate before huge joins | Stage selective keys first, index the stage, then join. |
| Huge detail table aggregated later | Aggregate early if grouping preserves semantics. |
| Join only tests existence | Replace row-producing join with EXISTS. |
| OR across different columns | Split into UNION ALL branches with duplicate guards. |
| Catch-all optional predicates | Dynamic SQL or targeted recompilation; avoid Col = @p OR @p IS NULL for hot paths. |
| Unsafe partition predicate | Rewrite to direct typed range on partition column. |
| Bad estimates from table variables/TVFs | Use temp tables, inline TVFs, or recompile depending on version and workload. |
Do not stage huge unfiltered tables or aggregate early unless the row reduction and semantic equivalence are proven.
Parameter Sensitivity
Parameter sniffing occurs when a plan compiled for one value is reused for a very different value. Confirm skew and compile/runtime values before applying fixes.
| Option | Best for | Caution |
|---|---|---|
OPTION (RECOMPILE) | Infrequent or highly variable statements | Adds compile CPU; plan not reused. |
OPTIMIZE FOR (@p = value) | Stable representative value | Can age badly as data changes. |
OPTIMIZE FOR UNKNOWN | Average distribution is acceptable | Can be mediocre for all cases. |
| Dynamic SQL | Optional predicates and varied shapes | Requires safe parameterization. |
| Query Store hints | SQL Server 2022+ or Azure SQL, no code change | Monitor regressions. |
| PSP optimization | SQL Server 2022+ with compatibility 160 | Only applies to eligible patterns. |
Execution Plan Checks
Watch these operators and warnings:
| Plan evidence | Likely action |
|---|---|
| Scan with residual predicate | Fix SARGability, key order, or filtered index. |
| Seek with high rows read | Add more selective key columns or rewrite residual predicate. |
| Key lookup repeated many times | Cover query or reduce outer rows first. |
| Sort spill or hash spill | Fix estimates, reduce rows/width, add order-compatible index. |
CONVERT_IMPLICIT on column | Align parameter/temp/source data types. |
| Estimate off by 10x+ | Check stats, skew, table variables, predicates, constraints. |
| Missing-index warning | Treat as candidate only; merge with existing indexes and workload. |
Statistics and Cardinality
Use statistics work when evidence points to stale or insufficient estimates:
DBCC SHOW_STATISTICS('dbo.TableName', 'IndexOrStatsName');
UPDATE STATISTICS dbo.TableName IndexOrStatsName WITH FULLSCAN;
For large partitioned tables, evaluate incremental statistics and filtered stats. Do not run broad fullscan updates in production without maintenance-window and blocking considerations.
Output Format
Respond with:
- Intake status: verified, unverified, disproved, needs diagnostic.
- Bottleneck evidence: plan nodes, reads, rows, estimates, warnings.
- Recommendation path: rewrite, index/stat change, or diagnostic, separated by allowed change type.
- Proof harness: result equivalence and before/after performance metrics.
- Risks: parameter sensitivity, write overhead, blocking, partition safety, remote pushdown.
References
../_shared/optimization-intake.md- mandatory intake checklist.../_shared/assumption-tracker.md- assumption status protocol.references/rewrite-proof-harnesses.md- join proof, temp type checker, and rewrite templates.references/dmv-diagnostic-queries.md- DMV queries for performance analysis.
FAQ
What does the query-optimization skill do?
This skill should be used when the user asks to optimize slow T-SQL queries, fix SQL Server performance regressions, improve SARGability, rewrite joins, prove whether joins can be removed, compare temp-table data types, select rewrite templates, diagnose parameter sniffing, evaluate query hints, inspect statistics/cardinality estimates, reduce spills or memory grants, use Query Store, or interpret plan evidence. PROACTIVELY activate for slow queries, scans vs seeks, implicit conversions, bad joins, tempdb spills, query rewrites, partition predicate safety, and before recommending indexes or hints. Provides: evidence-first workflow, rewrite templates, parameter-sniffing playbook, and gating rules before recommending indexes or hints.
How do I install query-optimization?
Run npx skills add https://github.com/josiahsiegel/claude-plugin-marketplace --skill query-optimization in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/query-optimization/ (personal) or .claude/skills/query-optimization/ (project).
Which AI agents can use query-optimization?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is query-optimization safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains query-optimization?
It is published by josiahsiegel in josiahsiegel/claude-plugin-marketplace. It has 189 recorded installs.
More from josiahsiegel/claude-plugin-marketplace
tailwindcss-advanced-layouts
josiahsiegel/claude-plugin-marketplace
Tailwind CSS advanced layout techniques including CSS Grid and Flexbox patterns. PROACTIVELY activate for: (1) building complex layouts with CSS Grid, (2) grid-template-areas via Tailwind v4 arbitrary values, (3) responsive grid (grid-cols-, auto-fit, minmax), (4) Flexbox patterns (flex-1, flex-grow, gap), (5) sticky headers and footers, (6) holy grail layout, (7) masonry-style layouts, (8) container queries (@container) with Tailwind, (9) subgrid usage, (10) aspect-ratio utilities, (11) magazine-style multi-column layouts. Provides: Grid template recipes, container-query patterns, holy-grail templates, masonry alternatives, and aspect-ratio examples.
tailwindcss-animations
josiahsiegel/claude-plugin-marketplace
Tailwind CSS animations and transitions including built-in utilities and custom keyframes. PROACTIVELY activate for: (1) animate- utilities (spin, ping, pulse, bounce), (2) custom @keyframes via @theme animate, (3) transition utilities (transition, duration, ease), (4) transforms (scale, rotate, translate) with transition, (5) prefers-reduced-motion: reduce, (6) Framer Motion / Motion One integration with Tailwind, (7) CSS scroll-driven animations (animation-timeline), (8) view transitions API with Tailwind, (9) hover, focus, group-hover transitions, (10) staggered list animations. Provides: animation utility reference, custom keyframe examples, reduced-motion pattern, Framer Motion integration, and scroll-driven animation recipes.
tailwindcss-mobile-first
josiahsiegel/claude-plugin-marketplace
Mobile-first responsive design patterns with Tailwind CSS v4 (2025-2026). PROACTIVELY activate for: (1) mobile-first design with Tailwind breakpoints (sm:, md:, lg:, xl:, 2xl:), (2) responsive utility ordering (default = mobile, then breakpoints), (3) responsive typography (text-base sm:text-lg lg:text-xl), (4) responsive grids and flexbox, (5) hide/show across breakpoints (hidden md:block), (6) max- breakpoints for desktop-down overrides, (7) container queries (@container) for component-level responsiveness, (8) safe-area insets and notch handling, (9) landscape vs portrait orientation, (10) touch vs hover (hover: with @media). Provides: breakpoint reference, mobile-first patterns, container-query examples, safe-area recipes, and touch/hover handling.
powershell-master
josiahsiegel/claude-plugin-marketplace
Complete PowerShell expertise system across ALL platforms (Windows/Linux/macOS). PROACTIVELY activate for: (1) ANY PowerShell task (scripts/modules/cmdlets), (2) CI/CD automation (GitHub Actions/Azure DevOps/Bitbucket), (3) Cross-platform scripting, (4) Module discovery and management (PSGallery), (5) Azure/AWS/Microsoft 365 automation, (6) Script debugging and optimization, (7) Best practices and security. Provides: PowerShell 7+ features, popular module expertise (Az, Microsoft.Graph, PnP, AWS Tools), PSGallery integration, platform-specific guidance, CI/CD pipeline patterns, cmdlet syntax mastery, and production-ready scripting patterns. Ensures professional-grade, cross-platform PowerShell automation following industry standards.
docker-best-practices
josiahsiegel/claude-plugin-marketplace
Comprehensive Docker best practices for images, containers, and production deployments. PROACTIVELY activate for: (1) writing production-ready Dockerfiles, (2) multi-stage builds for lean images, (3) base image selection (distroless, alpine, scratch, slim), (4) layer caching and ordering, (5) .dockerignore hygiene, (6) HEALTHCHECK and graceful shutdown, (7) non-root user and least-privilege patterns, (8) ENV vs ARG and secret handling, (9) tag/digest pinning and reproducibility, (10) Compose for local development. Provides: Dockerfile templates by language, image-size optimization checklist, .dockerignore template, HEALTHCHECK patterns, and Compose dev-stack examples.
git-master
josiahsiegel/claude-plugin-marketplace
Complete Git expertise system for ALL git operations. PROACTIVELY activate for: (1) ANY Git task (basic/advanced/dangerous), (2) Repository management, (3) Branch strategies and workflows, (4) Conflict resolution, (5) History rewriting/recovery, (6) Platform-specific operations (GitHub/Azure DevOps/Bitbucket), (7) Advanced commands (rebase/cherry-pick/filter-repo). Provides: complete Git command reference, safety guardrails for destructive operations, platform best practices, workflow strategies, reflog recovery techniques, and expert guidance for even the most risky operations. Always asks user preference for automatic commits vs manual control.
Popular data & databases skills
supabase-postgres-best-practices
supabase/agent-skills
Postgres best practices maintained by Supabase, for Postgres running anywhere. Load this skill BEFORE writing or changing anything that lives in a Postgres database: creating or altering tables and columns (including choosing column types), schema design, migrations and declarative schema files, RLS policies and the tests that verify them, indexes, triggers, database functions, queues and scheduled jobs (pgcron, pgmq), vector/semantic search (pgvector), and restoring dumps (pgrestore) or importing data. Also load it when diagnosing slow queries, high CPU, timeouts, EXPLAIN plans, connection exhaustion, locking, bloat, or rows visible to the wrong user or tenant. This is not just a performance guide — schema, migration, security, and SQL authoring tasks need these rules too, even for a one-column change or a single query.
prisma-client-api
prisma/skills
Prisma Client API reference covering model queries, filters, operators, and client methods. Use when writing database queries, using CRUD operations, filtering data, or configuring Prisma Client. Triggers on "prisma query", "findMany", "create", "update", "delete", "$transaction".
prisma-database-setup
prisma/skills
Deprecated compatibility name for prisma-orm-setup. Use only when a user or existing integration explicitly invokes prisma-database-setup; otherwise select prisma-orm-setup.
prisma-cli
prisma/skills
Prisma ORM 7 CLI reference for existing Prisma 7 applications or explicitly selected Prisma 7 workflows. Covers prisma init, generate, migrate, db, dev, studio, and mcp. For setup, connection repair, or Prisma 8, use prisma-orm-setup; not the Prisma Platform CLI.
prisma-postgres
prisma/skills
Deprecated compatibility name for prisma-postgres-setup. Use only when a user or existing integration explicitly invokes prisma-postgres; otherwise select prisma-postgres-setup.
prisma-driver-adapter-implementation
prisma/skills
Required reference for Prisma ORM 7 SQL driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter, Transaction, savepoint, result mapping, or DriverAdapterError behavior. Covers current transaction lifecycle, optional savepoint hooks, original database-error preservation, and verification.