sql-server-dba
Skill0 starsChanged 4 months agoMITView on GitHub
SQL Server DBA and query optimization assistant. Use when: (1) writing, reviewing, or optimizing T-SQL queries or stored procedures, (2) analyzing execution plans or slow queries, (3) designing indexes or reviewing index strategy, (4) creating or modifying stored procedures, (5) reviewing SQL for security (injection, permissions, data exposure), (6) troubleshooting SQL Server performance (DMVs, waits, blocking), (7) writing idempotent DDL scripts, (8) any .sql file editing or SQL-related code review. Also applies to Laravel/Eloquent queries hitting SQL Server (sqlsrv driver). Supports MySQL/PostgreSQL patterns as secondary — see references/cross-db.md.
In this repository5 other files it gives its agents.
- directSkill
- git-conflict-resolveSkill
- git-conflict-reviewSkill
- git-pr-mergeSkill
- pr-guardSkill
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 96
Every SP querying tenant-scoped tables MUST filter by Tenant_ID or @TenantID parameter.
- Very specific: line 230
Avoid over-indexing: each index costs INSERT/UPDATE/DELETE performance
- Distinctive: line 235
When reviewing SQL, report issues as:
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
SQL Server DBA
Expert SQL Server administration, T-SQL optimization, stored procedure development, and SQL code review. Primary focus: SQL Server with sqlsrv driver. Cross-DB patterns in references/cross-db.md.
Decision Tree
User request
|
+-- Writing/modifying a stored procedure? --> "SP Development" below
+-- Query is slow or needs optimization? --> "Query Optimization" below
+-- Reviewing SQL for security/quality? --> "Code Review" below
+-- Index strategy or schema question? --> "Index & Schema" below
+-- Performance investigation (DMVs)? --> references/performance-dmvs.md
+-- Cross-database (MySQL/PG/Oracle)? --> references/cross-db.mdSP Development
Naming & Structure
-- Prefix: sp_ for system-like, usp_ for user SPs
-- PascalCase: usp_GetOrderDetails, usp_GetDailySalesSummary
CREATE OR ALTER PROCEDURE [dbo].[sp_ProcedureName]
@TenantID INT,
@CustomerID INT,
@OptionalParam NVARCHAR(100) = NULL
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
-- Body here
END;Idempotent DDL Pattern
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
IF NOT EXISTS (SELECT 1 FROM sys.procedures WHERE name = 'sp_Example')
BEGIN
EXEC('CREATE PROCEDURE [dbo].[sp_Example] AS BEGIN RETURN; END');
END;
ALTER PROCEDURE [dbo].[sp_Example]
@TenantID INT
AS
BEGIN
SET NOCOUNT ON;
-- logic
END;
COMMIT;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK;
THROW;
END CATCH;Output Formatting
-- Single-object: use WITHOUT_ARRAY_WRAPPER + JSON_QUERY wrapping
SELECT @json = (
SELECT v.Order_ID, v.Order_Date,
(SELECT d.Product_ID, d.Product_Name
FROM OrderLines d
WHERE d.Order_ID = v.Order_ID
FOR JSON PATH) AS lines
FROM Orders v
WHERE v.Order_ID = @OrderID
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
);
-- Multi-row: FOR JSON PATH (returns array)
SELECT Order_ID, Order_Date
FROM Orders
WHERE Tenant_ID = @TenantID
FOR JSON PATH;Tenant Isolation (CRITICAL)
Every SP querying tenant-scoped tables MUST filter by Tenant_ID or @TenantID parameter. Never rely solely on RLS — belt-and-suspenders.
Query Optimization
Anti-Pattern: Functions in WHERE
-- BAD: prevents index seek
WHERE YEAR(Created_Date) = 2024
-- GOOD: sargable range
WHERE Created_Date >= '2024-01-01' AND Created_Date < '2025-01-01'Anti-Pattern: SELECT *
-- BAD: pulls all columns, breaks covering indexes
SELECT * FROM Orders v JOIN Customers p ON ...
-- GOOD: explicit columns
SELECT v.Order_ID, v.Order_Date, p.Full_Name
FROM Orders v
INNER JOIN Customers p ON v.Customer_ID = p.Customer_IDAnti-Pattern: Correlated Subqueries
-- BAD: executes subquery per row
SELECT p.Full_Name,
(SELECT COUNT(*) FROM Orders v WHERE v.Customer_ID = p.Customer_ID)
FROM Customers p
-- GOOD: window function or JOIN
SELECT p.Full_Name, COUNT(v.Order_ID) AS order_count
FROM Customers p
LEFT JOIN Orders v ON v.Customer_ID = p.Customer_ID
GROUP BY p.Full_NamePagination
-- BAD: OFFSET scales linearly
SELECT * FROM Products ORDER BY ID OFFSET 10000 ROWS FETCH NEXT 20 ROWS ONLY;
-- GOOD: keyset pagination
SELECT TOP 20 * FROM Products WHERE ID > @LastSeenID ORDER BY ID;Conditional Aggregation (replace N separate COUNT queries)
SELECT
COUNT(CASE WHEN Status = 1 THEN 1 END) AS pending,
COUNT(CASE WHEN Status = 2 THEN 1 END) AS confirmed,
COUNT(CASE WHEN Status = 3 THEN 1 END) AS completed
FROM Orders
WHERE Tenant_ID = @TenantID;Batch Operations
-- BAD: row-by-row INSERT
-- GOOD: batch with table-valued parameter or multi-row VALUES
INSERT INTO OrderLines (Order_ID, Product_ID, Notes)
VALUES
(@OrderID, 1, N'Note 1'),
(@OrderID, 2, N'Note 2'),
(@OrderID, 3, N'Note 3');Code Review Checklist
Security
- All dynamic SQL uses
sp_executesqlwith typed parameters — never string concat - No
EXEC('SELECT ... ' + @userInput)patterns - Tenant_ID filter on every tenant-scoped query
- Sensitive columns (national ID, phone, email) not in
SELECT *or unneeded result sets - SP permissions:
EXECUTE ASor role-based grants, notdboownership chaining
Performance
- No functions on indexed columns in WHERE clauses
- JOINs use INNER where possible (LEFT only when NULLs needed)
- No SELECT * in production queries
- EXISTS preferred over IN for subqueries
- Large result sets use pagination (OFFSET/FETCH or keyset)
- Temp tables for complex multi-step queries (not nested subqueries)
Code Quality
- SET NOCOUNT ON at SP top
- SET XACT_ABORT ON for transaction SPs
- BEGIN TRY / BEGIN CATCH for error handling
- Consistent UPPER for keywords (SELECT, FROM, WHERE)
- Column aliases use AS keyword
- Meaningful parameter names with @ prefix
Schema Awareness
- Column names match the project's schema reference exactly (case-sensitive)
- Data types match schema (NVARCHAR vs VARCHAR, DATETIME2 vs DATETIME)
- FK relationships used correctly (check schema for actual FK columns)
- Identity columns not targeted by INSERT unless
SET IDENTITY_INSERT ON
Index & Schema
Covering Index Design
-- Key columns = WHERE/JOIN, INCLUDE columns = SELECT-only
CREATE NONCLUSTERED INDEX IX_Orders_TenantDate
ON Orders (Tenant_ID, Order_Date)
INCLUDE (Customer_ID, Status, Sales_Rep_ID);Filtered Index
-- Index only active records — smaller, faster
CREATE NONCLUSTERED INDEX IX_Orders_Active
ON Orders (Tenant_ID, Order_Date)
WHERE Status IN (1, 2); -- pending, confirmedIndex Rules
- Lead with highest-selectivity column (usually Tenant_ID, then date/FK)
- Composite index column order must match query WHERE + ORDER BY
- INCLUDE columns for covering — avoids key lookups
- Avoid over-indexing: each index costs INSERT/UPDATE/DELETE performance
- Review unused indexes via
sys.dm_db_index_usage_stats
Review Output Format
When reviewing SQL, report issues as:
## [SEVERITY] [CATEGORY]: Brief Description
**Location**: SP/query name, line reference
**Issue**: What is wrong and why
**Fix**:
-- Before (bad)
-- After (good)
**Impact**: Performance gain / security fix / correctnessSeverity: CRITICAL > HIGH > MEDIUM > LOW
Resources
- Performance DMVs & monitoring: See references/performance-dmvs.md
- Cross-database patterns (MySQL, PostgreSQL, Oracle): See references/cross-db.md
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

