New advertisers: 50% off your first month with code FIRSTMONTHSee slots

Expert T-SQL and SQL Server tuning plugin for query, plan, index, and Azure SQL Database work.

version
2.0.10
GitHub stars
62
View on GitHub

What it does

  • Adds 3 commands (/analyze-query, /suggest-indexes, /explain-plan) and a tsql-expert agent for conversational optimization help
  • Covers six skills: query optimization, execution plan analysis, index strategies, Azure SQL tuning, advanced patterns, and T-SQL functions
  • Includes check-sargability.sql and index-analysis.sql scripts to find non-SARGable predicates and unhealthy indexes
  • Designed for database developers and DBAs diagnosing slow queries, parameter sniffing, or partition access in SQL Server and Azure SQL

Comprehensive T-SQL and SQL Server expertise for query optimization, execution plan analysis, index strategy, performance tuning, and Azure SQL Database. PROACTIVELY activate for: (1) schema-first query optimization and SARGability, (2) .sqlplan and ShowPlan XML triage, (3) index design and partition alignment, (4) parameter sniffing fixes, (5) Azure SQL Database tuning, (6) window functions and advanced patterns, (7) columnstore and In-Memory OLTP, (8) Query Store and IQP features. Includes: tsql-expert agent, 6 progressive disclosure skills, 3 optimization commands, diagnostic scripts.

Add marketplace

/plugin marketplace add JosiahSiegel/claude-plugin-marketplace

Run it inside Claude Code once, then install the plugin below.

Install

/plugin install tsql-master@claude-plugin-marketplace

Run it inside Claude Code after adding the marketplace.

Files

Discovered from source

Advanced T-SQL Patterns

Advanced techniques for complex SQL Server scenarios.

Quick Reference

Pattern Selection Guide

TaskPattern
Hierarchical dataRecursive CTE
Top N per groupROW_NUMBER + CTE
Correlated subquery alternativeCROSS/OUTER APPLY
Upsert (insert or update)MERGE
Capture modified rowsOUTPUT clause
Historical data trackingTemporal tables
High-throughput OLTPIn-Memory OLTP
Multiple aggregation levelsROLLUP/CUBE/GROUPING SETS

Common Table Expressions (CTEs)

Basic CTE

WITH RecentOrders AS (
    SELECT CustomerID, OrderDate, Amount
    FROM Orders
    WHERE OrderDate >= DATEADD(month, -3, GETDATE())
)
SELECT c.CustomerName, r.Amount
FROM Customers c
JOIN RecentOrders r ON c.CustomerID = r.CustomerID;

Multiple CTEs

WITH
Sales AS (
    SELECT ProductID, SUM(Amount) AS TotalSales FROM Orders GROUP BY ProductID
),
Inventory AS (
    SELECT ProductID, SUM(Quantity) AS TotalInventory FROM Stock GROUP BY ProductID
)
SELECT p.ProductName, s.TotalSales, i.TotalInventory
FROM Products p
LEFT JOIN Sales s ON p.ProductID = s.ProductID
LEFT JOIN Inventory i ON p.ProductID = i.ProductID;

Recursive CTE (Hierarchies)

WITH OrgChart AS (
    -- Anchor: Top-level (no manager)
    SELECT EmployeeID, Name, ManagerID, 0 AS Level,
           CAST(Name AS VARCHAR(1000)) AS Path
    FROM Employees
    WHERE ManagerID IS NULL

    UNION ALL

    -- Recursive: Subordinates
    SELECT e.EmployeeID, e.Name, e.ManagerID, oc.Level + 1,
           CAST(oc.Path + ' > ' + e.Name AS VARCHAR(1000))
    FROM Employees e
    JOIN OrgChart oc ON e.ManagerID = oc.EmployeeID
)
SELECT * FROM OrgChart
OPTION (MAXRECURSION 100);  -- Default is 100, max is 32767

CTE for Deleting Duplicates

WITH Duplicates AS (
    SELECT *,
           ROW_NUMBER() OVER (
               PARTITION BY Email
               ORDER BY CreatedDate DESC
           ) AS RowNum
    FROM Users
)
DELETE FROM Duplicates WHERE RowNum > 1;

APPLY Operator

CROSS APPLY (Inner Join Behavior)

-- Top 3 orders per customer
SELECT c.CustomerID, c.Name, o.OrderID, o.Amount
FROM Customers c
CROSS APPLY (
    SELECT TOP 3 OrderID, Amount
    FROM Orders
    WHERE CustomerID = c.CustomerID
    ORDER BY OrderDate DESC
) o;

OUTER APPLY (Left Join Behavior)

-- Last order per customer (including customers with no orders)
SELECT c.CustomerID, c.Name, o.LastOrderDate, o.LastOrderAmount
FROM Customers c
OUTER APPLY (
    SELECT TOP 1 OrderDate AS LastOrderDate, Amount AS LastOrderAmount
    FROM Orders
    WHERE CustomerID = c.CustomerID
    ORDER BY OrderDate DESC
) o;

APPLY with Table-Valued Function

-- Call function for each row
SELECT c.CustomerID, f.MonthlyTotal, f.OrderCount
FROM Customers c
CROSS APPLY dbo.GetCustomerMonthlyStats(c.CustomerID) f;

APPLY to Unpivot Columns

-- Transform columns to rows
SELECT ID, AttributeName, AttributeValue
FROM Products
CROSS APPLY (
    VALUES
        ('Color', Color),
        ('Size', Size),
        ('Weight', CAST(Weight AS VARCHAR))
) AS Unpivoted(AttributeName, AttributeValue)
WHERE AttributeValue IS NOT NULL;

MERGE Statement

Basic Upsert

MERGE INTO TargetTable AS t
USING SourceTable AS s
ON t.ID = s.ID
WHEN MATCHED THEN
    UPDATE SET t.Name = s.Name, t.Value = s.Value, t.UpdatedAt = GETDATE()
WHEN NOT MATCHED BY TARGET THEN
    INSERT (ID, Name, Value, CreatedAt)
    VALUES (s.ID, s.Name, s.Value, GETDATE())
WHEN NOT MATCHED BY SOURCE THEN
    DELETE
OUTPUT $action, inserted.*, deleted.*;

MERGE with Conditions

MERGE INTO Products AS t
USING StagingProducts AS s
ON t.ProductID = s.ProductID
WHEN MATCHED AND s.Price <> t.Price THEN
    UPDATE SET t.Price = s.Price, t.LastModified = GETDATE()
WHEN MATCHED AND s.Discontinued = 1 THEN
    DELETE
WHEN NOT MATCHED THEN
    INSERT (ProductID, Name, Price) VALUES (s.ProductID, s.Name, s.Price);

OUTPUT Clause

Capture Inserted Rows

DECLARE @InsertedRows TABLE (ID INT, Name VARCHAR(100));

INSERT INTO Customers (Name, Email)
OUTPUT inserted.CustomerID, inserted.Name INTO @InsertedRows
VALUES ('John', 'john@email.com'), ('Jane', 'jane@email.com');

SELECT * FROM @InsertedRows;

Capture Updated Rows (Before and After)

UPDATE Products
SET Price = Price * 1.1
OUTPUT deleted.ProductID, deleted.Price AS OldPrice, inserted.Price AS NewPrice
WHERE Category = 'Electronics';

Capture Deleted Rows

DELETE FROM ExpiredOrders
OUTPUT deleted.*
INTO OrderArchive
WHERE ExpiryDate < DATEADD(year, -1, GETDATE());

Advanced Grouping

ROLLUP (Hierarchical Subtotals)

SELECT
    COALESCE(Region, 'Total') AS Region,
    COALESCE(Product, 'All Products') AS Product,
    SUM(Sales) AS TotalSales
FROM SalesData
GROUP BY ROLLUP (Region, Product);
-- Groups: (Region, Product), (Region), ()

CUBE (All Combinations)

SELECT Region, Product, SUM(Sales) AS TotalSales
FROM SalesData
GROUP BY CUBE (Region, Product);
-- Groups: (Region, Product), (Region), (Product), ()

GROUPING SETS (Custom Combinations)

SELECT Region, Product, Year, SUM(Sales)
FROM SalesData
GROUP BY GROUPING SETS (
    (Region, Product),
    (Region, Year),
    (Product),
    ()
);

Identify Grouping Level

SELECT
    CASE WHEN GROUPING(Region) = 1 THEN 'All' ELSE Region END AS Region,
    CASE WHEN GROUPING(Product) = 1 THEN 'All' ELSE Product END AS Product,
    SUM(Sales) AS TotalSales,
    GROUPING_ID(Region, Product) AS GroupLevel
    -- GroupLevel: 0 = both, 1 = Product rolled up, 2 = Region rolled up, 3 = both
FROM SalesData
GROUP BY ROLLUP (Region, Product);

Temporal Tables (SQL 2016+)

Create System-Versioned Table

CREATE TABLE Products (
    ProductID INT PRIMARY KEY,
    Name NVARCHAR(100),
    Price DECIMAL(18,2),
    ValidFrom DATETIME2 GENERATED ALWAYS AS ROW START,
    ValidTo DATETIME2 GENERATED ALWAYS AS ROW END,
    PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo)
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.ProductsHistory));

Query Historical Data

-- Point in time
SELECT * FROM Products
FOR SYSTEM_TIME AS OF '2024-01-01 12:00:00';

-- Time range
SELECT * FROM Products
FOR SYSTEM_TIME BETWEEN '2024-01-01' AND '2024-06-30';

-- All history
SELECT * FROM Products
FOR SYSTEM_TIME ALL;

In-Memory OLTP

Create Memory-Optimized Table

-- First add filegroup
ALTER DATABASE YourDB
ADD FILEGROUP MemOptFG CONTAINS MEMORY_OPTIMIZED_DATA;

ALTER DATABASE YourDB
ADD FILE (NAME = 'MemOptFile', FILENAME = 'C:\Data\MemOpt') TO FILEGROUP MemOptFG;

-- Create table
CREATE TABLE OrdersMemOpt (
    OrderID INT NOT NULL PRIMARY KEY NONCLUSTERED HASH WITH (BUCKET_COUNT = 1000000),
    CustomerID INT NOT NULL INDEX IX_Customer NONCLUSTERED HASH WITH (BUCKET_COUNT = 100000),
    OrderDate DATETIME2 NOT NULL,
    Amount DECIMAL(18,2) NOT NULL,
    INDEX IX_Date NONCLUSTERED (OrderDate)
) WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_AND_DATA);

Natively Compiled Procedure

CREATE PROCEDURE InsertOrderFast
    @CustomerID INT,
    @Amount DECIMAL(18,2)
WITH NATIVE_COMPILATION, SCHEMABINDING
AS
BEGIN ATOMIC WITH (TRANSACTION ISOLATION LEVEL = SNAPSHOT, LANGUAGE = N'English')
    INSERT INTO dbo.OrdersMemOpt (OrderID, CustomerID, OrderDate, Amount)
    VALUES (NEXT VALUE FOR dbo.OrderSeq, @CustomerID, SYSDATETIME(), @Amount);
END;

Table-Valued Constructor

VALUES as Table

SELECT * FROM (
    VALUES
        (1, 'Apple', 1.50),
        (2, 'Banana', 0.75),
        (3, 'Orange', 2.00)
) AS Products(ID, Name, Price);

Use in MERGE

MERGE INTO Products AS t
USING (VALUES
    (1, 'Apple', 1.60),
    (2, 'Banana', 0.80)
) AS s(ID, Name, Price)
ON t.ID = s.ID
WHEN MATCHED THEN UPDATE SET Price = s.Price
WHEN NOT MATCHED THEN INSERT VALUES (s.ID, s.Name, s.Price);

Sequences

Create and Use Sequence

CREATE SEQUENCE OrderSeq
    AS INT START WITH 1 INCREMENT BY 1;

-- Get next value
SELECT NEXT VALUE FOR OrderSeq;

-- Use in INSERT
INSERT INTO Orders (OrderID, CustomerID)
VALUES (NEXT VALUE FOR OrderSeq, @CustomerID);

-- Use as default
ALTER TABLE Orders
ADD CONSTRAINT DF_OrderID DEFAULT NEXT VALUE FOR OrderSeq FOR OrderID;

Readme

T-SQL Master

Comprehensive T-SQL and SQL Server expertise for schema-first query optimization, ShowPlan XML analysis, index strategy, performance tuning, and Azure SQL Database.

Features

  • Progressive Disclosure Skills - Deep knowledge organized for efficient loading
  • Expert Agent - Conversational T-SQL optimization assistance
  • Optimization Commands - Automated query and index analysis
  • Diagnostic Scripts - Ready-to-use SQL Server health checks

Installation

From Marketplace (Recommended)

/plugin marketplace add JosiahSiegel/claude-plugin-marketplace
/plugin install tsql-master@claude-plugin-marketplace

Local Installation

git clone https://github.com/JosiahSiegel/claude-plugin-marketplace.git
cp -r claude-plugin-marketplace/plugins/tsql-master ~/.claude/plugins/local/

Usage

Just ask about T-SQL optimization:

  • "Optimize this query for better performance"
  • "What indexes should I create for this table?"
  • "Help me understand this execution plan or .sqlplan file"
  • "Why is my partitioned table reading every partition?"
  • "Prove whether this join can be removed or replaced with EXISTS"
  • "How do I fix parameter sniffing?"
  • "Best practices for Azure SQL Database"

Components

Agent

NamePurpose
tsql-expertPrimary expert for T-SQL optimization and SQL Server performance

Skills

SkillPurpose
tsql-functionsComplete T-SQL function reference (string, date, window, JSON, XML)
query-optimizationSchema-first optimization, SARGability, joins, hints, statistics, rewrite proof
execution-plan-analysis.sqlplan and ShowPlan XML triage, plan warnings, estimates, partition access
index-strategiesClustered, nonclustered, columnstore, filtered, partition-aligned indexes
azure-sql-optimizationAzure SQL Database features, DTU/vCore, Hyperscale
advanced-patternsCTEs, APPLY, MERGE, temporal tables, In-Memory OLTP

Commands

CommandPurpose
/analyze-queryAnalyze query for optimization opportunities
/suggest-indexesRecommend indexes for query patterns
/explain-planHelp interpret execution plan operators

Scripts

ScriptPurpose
check-sargability.sqlFind queries with SARGability issues
index-analysis.sqlComprehensive index health check

SQL Server Version Support

VersionCompatibility LevelKey Features
SQL Server 2016130Query Store, JSON, Temporal Tables
SQL Server 2017140STRING_AGG, Adaptive Joins, TRIM
SQL Server 2019150Batch Mode on Rowstore, Scalar UDF Inlining
SQL Server 2022160GREATEST/LEAST, DATETRUNC, GENERATE_SERIES, PSP
Azure SQL DatabaseLatestAutomatic Tuning, Hyperscale, Serverless

Key Optimization Topics

Query Performance

  • SARGable query patterns
  • Join optimization (LOOP, MERGE, HASH)
  • Query hints (RECOMPILE, OPTIMIZE FOR, MAXDOP)
  • Parameter sniffing solutions
  • Statistics and cardinality estimation

Index Strategy

  • Clustered index key selection
  • Covering indexes with INCLUDE
  • Filtered indexes for specific patterns
  • Columnstore for analytics
  • Index maintenance and fragmentation

Azure SQL Database

  • DTU vs vCore selection
  • Automatic tuning
  • Query Performance Insight
  • Hyperscale architecture
  • Serverless configuration

Advanced Patterns

  • Recursive CTEs for hierarchies
  • CROSS/OUTER APPLY techniques
  • MERGE for upsert operations
  • Window functions and framing
  • In-Memory OLTP tables

Plugin Structure

tsql-master/
├── .claude-plugin/
│   └── plugin.json
├── agents/
│   └── tsql-expert.md
├── skills/
│   ├── tsql-functions/
│   │   ├── SKILL.md
│   │   └── references/
│   ├── query-optimization/
│   │   ├── SKILL.md
│   │   └── references/
│   ├── execution-plan-analysis/
│   │   ├── SKILL.md
│   │   └── references/
│   ├── index-strategies/
│   │   ├── SKILL.md
│   │   └── references/
│   ├── azure-sql-optimization/
│   │   ├── SKILL.md
│   │   └── references/
│   └── advanced-patterns/
│       ├── SKILL.md
│       └── references/
├── commands/
│   ├── analyze-query.md
│   ├── suggest-indexes.md
│   └── explain-plan.md
├── scripts/
│   ├── check-sargability.sql
│   ├── index-analysis.sql
│   └── README.md
└── README.md

What's New in 2.0.0

  • Progressive disclosure skills - Knowledge organized into lean SKILL.md files with detailed references
  • Restructured agent - Proper example blocks and tool configuration
  • New commands - /analyze-query, /suggest-indexes, /explain-plan
  • Diagnostic scripts - SQL scripts for SARGability and index analysis
  • Enhanced Azure SQL coverage - Hyperscale, serverless, automatic tuning
  • SQL Server 2022 features - GENERATE_SERIES, DATETRUNC, PSP optimization

Technical Details

Support

Details

Marketplace
JosiahSiegel/claude-plugin-marketplace
Source
plugins/tsql-master
Author
Josiah Siegel
Category
Community
Keywords
tsql, sql-server, azure-sql, query-optimization, performance-tuning, indexing, execution-plan, columnstore, in-memory-oltp, query-store, parameter-sniffing, intelligent-query-processing, database, microsoft, transact-sql, window-functions, cte, json, sargability, dmv, statistics
Listed since
Apr 7, 2026

More from JosiahSiegel/claude-plugin-marketplace

All 43

Similar to tsql-master

More Databases