/tsql-master:advanced-patternsfrom tsql-master
Advanced T-SQL patterns and techniques for SQL Server and Azure SQL. Provides pattern catalog with examples, performance tradeoffs, and copy-pasteable templates for common advanced query shapes.
Ships in tsql-master. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Advanced techniques for complex SQL Server scenarios.
| Task | Pattern |
|---|---|
| Hierarchical data | Recursive CTE |
| Top N per group | ROW_NUMBER + CTE |
| Correlated subquery alternative | CROSS/OUTER APPLY |
| Upsert (insert or update) | MERGE |
| Capture modified rows | OUTPUT clause |
| Historical data tracking | Temporal tables |
| High-throughput OLTP | In-Memory OLTP |
| Multiple aggregation levels | ROLLUP/CUBE/GROUPING SETS |
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;
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;
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
WITH Duplicates AS (
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY Email
ORDER BY CreatedDate DESC
) AS RowNum
FROM Users
)
DELETE FROM Duplicates WHERE RowNum > 1;
-- 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;
-- 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;
-- Call function for each row
SELECT c.CustomerID, f.MonthlyTotal, f.OrderCount
FROM Customers c
CROSS APPLY dbo.GetCustomerMonthlyStats(c.CustomerID) f;
-- 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 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 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);
DECLARE @InsertedRows TABLE (ID INT, Name VARCHAR(100));
INSERT INTO Customers (Name, Email)
OUTPUT inserted.CustomerID, inserted.Name INTO @InsertedRows
VALUES ('John', '[email protected]'), ('Jane', '[email protected]');
SELECT * FROM @InsertedRows;
UPDATE Products
SET Price = Price * 1.1
OUTPUT deleted.ProductID, deleted.Price AS OldPrice, inserted.Price AS NewPrice
WHERE Category = 'Electronics';
DELETE FROM ExpiredOrders
OUTPUT deleted.*
INTO OrderArchive
WHERE ExpiryDate < DATEADD(year, -1, GETDATE());
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), ()
SELECT Region, Product, SUM(Sales) AS TotalSales
FROM SalesData
GROUP BY CUBE (Region, Product);
-- Groups: (Region, Product), (Region), (Product), ()
SELECT Region, Product, Year, SUM(Sales)
FROM SalesData
GROUP BY GROUPING SETS (
(Region, Product),
(Region, Year),
(Product),
()
);
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);
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));
-- 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;
-- 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);
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;
SELECT * FROM (
VALUES
(1, 'Apple', 1.50),
(2, 'Banana', 0.75),
(3, 'Orange', 2.00)
) AS Products(ID, Name, Price);
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);
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;
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
t-sql, sql-server, advanced-query-patterns, cte, window-functions
6 skills in this plugin
/azure-sql-optimizationAzure SQL Database optimization and platform-specific features.
PROACTIVELY activate for: (1) Azure SQL Database optimization, (2) DTU vs vCore selection and right-sizing, (3) automatic tuning (force last good plan, create/drop index), (4) Hyperscale tier and read replicas, (5) Serverless tier and auto-pause, (6) Azure SQL performance monitoring (Query Performance Insight, Intelligent Insights), (7) elastic pools, (8) Always Encrypted with secure enclaves, (9) Managed Instance vs Azure SQL DB tradeoffs, (10) failover groups and geo-replication.
Provides: tier-selection matrix, automatic-tuning enablement steps, Hyperscale architecture overview, monitoring queries, and elastic pool sizing guidance.
/execution-plan-analysisThis skill should be used when the user asks to analyze SQL Server execution plans, .sqlplan files, ShowPlan XML, actual vs estimated plans, plan warnings, or operator costs. PROACTIVELY activate for: .sqlplan triage, ShowPlan XML inspection, high-cost operator ranking, scan vs seek review, residual predicate analysis, CONVERT_IMPLICIT warnings, bad row estimates, cardinality-estimation warnings, partition elimination verification, missing-index suggestions, unused-index warnings, spills, key lookups, sorts, hash joins, and plan-regression evidence gathering.
Provides: plan triage workflow, operator-cost ranking heuristics, warning interpretation rubric, and rewrite/index recommendation gating.
/index-strategiesThis 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.
/query-optimizationThis 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.
/tsql-functionsComplete T-SQL function reference for SQL Server and Azure SQL Database.
PROACTIVELY activate for: (1) string functions (CONCAT_WS, STRING_SPLIT, STRING_AGG, TRIM, REPLACE, LEFT/RIGHT/SUBSTRING), (2) date/time functions (DATEADD, DATEDIFF, FORMAT, DATETRUNC, AT TIME ZONE), (3) math and conversion functions (CAST, CONVERT, TRY_CAST, ROUND, FLOOR, CEILING), (4) window/ranking functions (ROW_NUMBER, RANK, LEAD/LAG, FIRST_VALUE, LAST_VALUE, NTILE), (5) JSON functions (JSON_VALUE, JSON_QUERY, JSON_MODIFY, OPENJSON), (6) XML functions (FOR XML, .nodes, .value), (7) aggregate functions and GROUP BY extensions, (8) system and metadata functions (sys.* views, OBJECT_ID, OBJECT_NAME).
Provides: function catalog grouped by category, version-availability matrix (SQL 2016+/2019+/2022+), and worked examples for each function family.
npx claudepluginhub josiahsiegel/claude-plugin-marketplace --plugin tsql-masterOther plugins' skills for the same job