plugins/tsql-master/skills/index-strategies/SKILL.md
This skill should be used when the user asks to design, review, add, drop, consolidate, or tune SQL Server indexes. PROACTIVELY activate for clustered vs nonclustered design, covering indexes and INCLUDE columns, filtered indexes, columnstore indexes, missing-index DMV interpretation, duplicate or unused indexes, index maintenance, fragmentation, fill factor, compression, partition-aligned indexes, partition elimination proof, huge-table index constraints, online/resumable rebuilds, and index changes for slow T-SQL queries. Provides: index-design decision tree, workload-aware tradeoff checklist, DMV interpretation guidance, and maintenance/rebuild patterns.
npx skillsauth add JosiahSiegel/claude-plugin-marketplace index-strategiesInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Comprehensive guide to SQL Server index design and optimization. Index advice must be workload-aware and constraint-aware: the best index for one query can be harmful for writes, storage, maintenance, partition switching, or other critical queries.
Before recommending index DDL, collect or mark unknown:
Use ../_shared/optimization-intake.md and ../_shared/assumption-tracker.md. Do not present missing-index DMV output as final design without existing-index and workload review.
| Type | Best for | Cautions | |---|---|---| | Clustered | Primary table order, range access, narrow stable key | Expensive to change; clustering key is included in nonclustered indexes. | | Nonclustered | Query-specific seeks, joins, ordering | Adds write and storage overhead. | | Covering | Avoiding repeated key lookups | INCLUDE bloat can hurt cache and writes. | | Filtered | Stable, selective subsets | Query predicate must imply filter; parameters can block use. | | Columnstore | Analytics, scans, aggregations, compression | Small updates and singleton lookups can suffer. | | Unique | Enforcing business rules and optimizer proof | Must match real semantics. |
Map query columns by role:
| Role | Index design implication |
|---|---|
| Equality predicates | Usually first key columns, ordered by selectivity and workload reuse. |
| Join keys | Useful as seek keys and join order support. |
| Range predicates | Usually after equality keys; only one range can be deeply seekable. |
| ORDER BY / GROUP BY | Consider key order to avoid sorts or stream aggregates. |
| Selected columns | INCLUDE only when lookup cost justifies storage/write cost. |
Example:
CREATE NONCLUSTERED INDEX IX_Orders_CustomerDate
ON dbo.Orders(CustomerID, OrderDate)
INCLUDE (Status, TotalAmount);
An index cannot fully help if predicates are non-SARGable or types mismatch. Confirm parameter, temp-table, and source column types before adding indexes. Fix CONVERT_IMPLICIT on join/filter columns first when possible.
Before adding a new index:
Classify the recommendation:
| Constraint | Safer response | |---|---| | Cannot add indexes | Query rewrite, stats, hints, temp staging, or Query Store hints. | | Cannot change huge-table indexes | Add narrow filtered index, indexed staging table, or reduce rows before touching table. | | Online index not allowed | Plan maintenance window and blocking risk; consider resumable where supported. | | Partition switching required | Prefer aligned indexes; avoid nonaligned indexes unless explicitly accepted. | | Heavy write workload | Minimize key width and INCLUDE list; prove read benefit. | | Storage constrained | Consolidate duplicates and avoid speculative covering indexes. |
Ideal clustered keys are narrow, unique, static, and usually ever-increasing for OLTP insert patterns.
CREATE CLUSTERED INDEX CIX_Orders ON dbo.Orders(OrderID);
Avoid wide composite clustered keys unless they match a deliberate access pattern and write trade-off. Random GUID clustering can cause page splits; consider NEWSEQUENTIALID(), a surrogate key, or fill-factor strategy when appropriate.
Covering indexes avoid lookups when the lookup cost is significant.
CREATE NONCLUSTERED INDEX IX_Orders_CustomerID_Cover
ON dbo.Orders(CustomerID)
INCLUDE (OrderDate, TotalAmount, Status);
Use INCLUDE columns for output-only columns, not for filtering or ordering. Keep INCLUDE lists minimal; wide includes can be worse than occasional lookups.
Filtered indexes are strong for stable subsets:
CREATE NONCLUSTERED INDEX IX_Orders_Open_ByCustomer
ON dbo.Orders(CustomerID, OrderDate)
WHERE Status = 'Open';
Requirements:
Use columnstore for analytic scans, aggregations, and compression.
CREATE CLUSTERED COLUMNSTORE INDEX CCI_FactSales
ON dbo.FactSales;
CREATE NONCLUSTERED COLUMNSTORE INDEX NCCI_Orders_Analysis
ON dbo.Orders(OrderDate, ProductID, Quantity, Amount)
WHERE Status = 'Completed';
Best practices:
REORGANIZE to compress delta rowgroups and merge rowgroups.For partitioned tables, index design must account for elimination and maintenance.
Verify:
RANGE LEFT vs RANGE RIGHT.Do not claim partition elimination from a date filter unless it targets the partitioning column in a compatible, SARGable form or a trusted constraint proves equivalence. See references/partition-alignment-analysis.md.
Fragmentation rules are workload-dependent, but a common starting point is:
| Fragmentation | Typical action | |---|---| | Less than 5% | No action. | | 5-30% | Reorganize if page count and workload justify it. | | More than 30% | Rebuild if maintenance window, edition, and blocking allow it. |
ALTER INDEX IX_Orders_CustomerID ON dbo.Orders REORGANIZE;
ALTER INDEX IX_Orders_CustomerID ON dbo.Orders
REBUILD WITH (ONLINE = ON, RESUMABLE = ON, MAX_DURATION = 60);
Update statistics after meaningful index changes when auto-created stats or sampled stats are insufficient:
UPDATE STATISTICS dbo.Orders IX_Orders_CustomerID WITH FULLSCAN;
Index usage since last restart or database attach:
SELECT
OBJECT_SCHEMA_NAME(i.object_id) AS SchemaName,
OBJECT_NAME(i.object_id) AS TableName,
i.name AS IndexName,
ius.user_seeks,
ius.user_scans,
ius.user_lookups,
ius.user_updates
FROM sys.indexes AS i
LEFT JOIN sys.dm_db_index_usage_stats AS ius
ON i.object_id = ius.object_id
AND i.index_id = ius.index_id
AND ius.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.object_id, 'IsUserTable') = 1
ORDER BY COALESCE(ius.user_seeks, 0) + COALESCE(ius.user_scans, 0) DESC;
Missing-index candidates:
SELECT
migs.avg_user_impact AS ImpactPercent,
mid.statement AS TableName,
mid.equality_columns,
mid.inequality_columns,
mid.included_columns
FROM sys.dm_db_missing_index_groups AS mig
JOIN sys.dm_db_missing_index_group_stats AS migs
ON mig.index_group_handle = migs.group_handle
JOIN sys.dm_db_missing_index_details AS mid
ON mig.index_handle = mid.index_handle
WHERE mid.database_id = DB_ID()
ORDER BY migs.avg_user_impact DESC;
Provide:
../_shared/optimization-intake.md - pre-optimization intake.../_shared/assumption-tracker.md - assumption status tracking.references/partition-alignment-analysis.md - partition scheme and elimination analysis.development
This skill should be used when the user asks to train, debug, scale, or improve ML models. PROACTIVELY activate for: (1) PyTorch, TensorFlow/Keras, JAX, Flax, Hugging Face Trainer/Accelerate training loops, (2) distributed training, DDP/FSDP/DeepSpeed, TPU/GPU setup, (3) mixed precision AMP/bf16, gradient accumulation, checkpointing, seeding, (4) overfitting, imbalance, loss functions, regularization, LR schedules, warmup, (5) memory optimization, gradient checkpointing, offloading, quantization-aware training. Provides: reproducible training best practices across deep learning and classical ML.
development
This skill should be used when the user asks to productionize, track, version, govern, monitor, or automate ML systems. PROACTIVELY activate for: (1) MLflow, Weights & Biases, Neptune, Comet, ClearML experiment tracking, (2) model registry, model versioning, artifact lineage, reproducibility, (3) Kubeflow, SageMaker Pipelines, Vertex AI Pipelines, Azure ML pipelines, Databricks workflows, (4) CI/CD, continuous training/evaluation, A/B tests, canary/shadow deployments, (5) drift detection, model monitoring, data validation, responsible AI governance. Provides: end-to-end MLOps architecture and operational safeguards.
development
This skill should be used when the user asks to optimize, export, serve, compress, or accelerate ML inference. PROACTIVELY activate for: (1) latency, throughput, p95/p99, batching, concurrency, KV cache, memory, or cost issues, (2) quantization INT8/INT4, GPTQ, AWQ, bitsandbytes, pruning, sparsity, distillation, (3) ONNX export, ONNX Runtime, TensorRT, TorchScript, torch.compile, XLA, OpenVINO, Core ML, TFLite, (4) Triton, TorchServe, TF Serving, BentoML, Seldon, KServe configuration, (5) edge deployment, CPU/GPU/TPU/Inferentia serving. Provides: hardware-aware inference optimization and safe benchmarking.
testing
This skill should be used when the user asks to tune hyperparameters, run sweeps, optimize search spaces, or use AutoML. PROACTIVELY activate for: (1) Optuna, Ray Tune, FLAML, AutoGluon, Hyperopt, Nevergrad, KerasTuner, W&B sweeps, (2) grid search, random search, Bayesian optimization, TPE, Gaussian processes, evolutionary search, (3) ASHA, Hyperband, successive halving, multi-fidelity optimization, population-based training, (4) learning-rate finder, batch-size search, early stopping, pruning, (5) reproducible sweep design and experiment analysis. Provides: budget-aware hyperparameter search strategy.