sql-toolkit
Skill1 starsChanged 35 days agoMITView on GitHub
SQL Server code review and universal SQL performance optimization — security, anti-patterns, indexing, pagination, monitoring. Use when reviewing SQL scripts, stored procedures, Dapper queries, or tuning query performance.
2 other projects use a version of this.
Adopted by
Most recently taken up by
- albertdobmeyer/openskill-forgetheir own version, first seen Apr 2, 2026
- GPTtang/skill-atlastheir own version, first seen Mar 22, 2026
Other versions2 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 2
- GPTtang/skill-atlas★ 4same name
- albertdobmeyer/openskill-forge★ 1same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository14 other files it gives its agents.
- appinsights-instrumentationSkill
- csharp-toolkitSkill
- delegateSkill
- deploy-verifySkill
- diagnoseSkill
- documentation-writerSkill
- flywheelSkill
- grill-meSkill
- javascript-typescript-jestSkill
- microsoft-docsSkill
- nuget-managerSkill
- performance-optimizationSkill
- python-fastapi-pytestSkill
- tddSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
13 rules. About 0 are common, 5 are distinctive, and 8 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
8
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 23
All user inputs must be parameterized — no string concatenation in dynamic SQL.
- Very specific: line 24
If dynamic SQL is unavoidable, use sp_executesql with typed parameters.
- Very specific: line 25
Use QUOTENAME() for dynamic object names (table/column references).
- Very specific: line 30
Avoid WITH GRANT OPTION unless explicitly required.
- Distinctive: line 38
Don't wrap indexed columns in functions — kills index seeks:
- Very specific: line 48
Never SELECT * — list needed columns explicitly.
- Very specific: line 49
Use EXISTS instead of COUNT(*) > 0 for existence checks.
- Very specific: line 50
Prefer JOIN over correlated subqueries when the optimizer can't flatten them.
- Very specific: line 51
Use OPTION (RECOMPILE) sparingly — only for parameter-sniffing issues with skewed data.
- Distinctive: line 52
Check estimated vs actual row counts in execution plans for cardinality mismatches.
- Distinctive: line 155
Keep transactions as short as possible — long transactions hold locks.
- Distinctive: line 156
Don't do HTTP calls or file I/O inside a transaction.
- Very specific: line 157
Use SET XACT_ABORT ON in stored procs so errors auto-rollback.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 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 Toolkit
Review and optimize the provided SQL (or the full file) for security, performance, and quality.
Security
Injection Prevention
-- Bad: string concatenation
SET @sql = 'SELECT * FROM Users WHERE Id = ' + @input;
-- Good: parameterized
EXEC sp_executesql N'SELECT * FROM Users WHERE Id = @id', N'@id INT', @id = @input;- All user inputs must be parameterized — no string concatenation in dynamic SQL.
- If dynamic SQL is unavoidable, use
sp_executesqlwith typed parameters. - Use
QUOTENAME()for dynamic object names (table/column references).
Access Control
- Grant minimum required permissions. Use roles, not direct user grants.
- Stored procs should use
EXECUTE ASonly when necessary. - Avoid
WITH GRANT OPTIONunless explicitly required.
Query Optimization
Index Usage
- Columns in WHERE, JOIN, ORDER BY should have supporting indexes.
- Don't wrap indexed columns in functions — kills index seeks:
-- Bad: function on column prevents index use
WHERE YEAR(CreatedOn) = 2024
-- Good: range predicate uses index
WHERE CreatedOn >= '2024-01-01' AND CreatedOn < '2025-01-01'Query Patterns
- Never
SELECT *— list needed columns explicitly. - Use
EXISTSinstead ofCOUNT(*) > 0for existence checks. - Prefer
JOINover correlated subqueries when the optimizer can't flatten them. - Use
OPTION (RECOMPILE)sparingly — only for parameter-sniffing issues with skewed data. - Check estimated vs actual row counts in execution plans for cardinality mismatches.
Subquery Optimization
-- Bad: correlated subquery
SELECT p.product_name, p.price
FROM products p
WHERE p.price > (SELECT AVG(price) FROM products p2 WHERE p2.category_id = p.category_id);
-- Good: window function
SELECT product_name, price
FROM (
SELECT product_name, price,
AVG(price) OVER (PARTITION BY category_id) as avg_category_price
FROM products
) ranked
WHERE price > avg_category_price;JOIN Optimization
-- Bad: LEFT JOIN + WHERE filter on right table (converts to INNER JOIN behavior with scan)
SELECT o.*, c.name FROM orders o
LEFT JOIN customers c ON o.customer_id = c.id
WHERE c.status = 'active';
-- Good: INNER JOIN when you need the filter
SELECT o.id, o.total_amount, c.name FROM orders o
INNER JOIN customers c ON o.customer_id = c.id AND c.status = 'active'
WHERE o.created_at > '2024-01-01';Pagination
-- Good: keyset pagination (fast for deep pages)
WHERE Id > @LastId ORDER BY Id FETCH NEXT 50 ROWS ONLY
-- Acceptable: OFFSET for shallow pages
ORDER BY Id OFFSET @Skip ROWS FETCH NEXT @Take ROWS ONLY
-- Bad: OFFSET for deep pages (scans all skipped rows)
ORDER BY created_at DESC OFFSET 10000 ROWS FETCH NEXT 20 ROWS ONLYAggregation Optimization
-- Bad: multiple separate queries
SELECT COUNT(*) FROM orders WHERE status = 'pending';
SELECT COUNT(*) FROM orders WHERE status = 'shipped';
-- Good: conditional aggregation
SELECT
COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count,
COUNT(CASE WHEN status = 'shipped' THEN 1 END) as shipped_count
FROM orders;OR vs UNION
-- Bad: complex OR (optimizer may struggle)
SELECT * FROM products
WHERE (category = 'electronics' AND price < 1000) OR (category = 'books' AND price < 50);
-- Good: UNION ALL for separate index paths
SELECT * FROM products WHERE category = 'electronics' AND price < 1000
UNION ALL
SELECT * FROM products WHERE category = 'books' AND price < 50;Anti-Patterns
N+1 Queries (via Dapper)
// Bad: N+1 — one query per user
foreach (var user in users)
user.Orders = await conn.QueryAsync<Order>("SELECT * FROM Orders WHERE UserId = @Id", new { user.Id });
// Good: single query + split
var sql = "SELECT u.*, o.* FROM Users u LEFT JOIN Orders o ON u.Id = o.UserId WHERE u.Id IN @Ids";
var result = await conn.QueryAsync<User, Order, User>(sql, (u, o) => { ... }, new { Ids = userIds });DISTINCT Masking Bad Joins
-- Bad: DISTINCT hides a missing join condition
SELECT DISTINCT u.Name FROM Users u, Orders o WHERE u.Id = o.UserId
-- Good: proper join, no DISTINCT needed
SELECT u.Name FROM Users u INNER JOIN Orders o ON u.Id = o.UserId GROUP BY u.NameImplicit Conversions
-- Bad: varchar param against nvarchar column → implicit conversion + scan
WHERE NVarCharColumn = @VarCharParam
-- Good: match types
WHERE NVarCharColumn = @NVarCharParamTransaction Scope
- Keep transactions as short as possible — long transactions hold locks.
- Don't do HTTP calls or file I/O inside a transaction.
- Use
SET XACT_ABORT ONin stored procs so errors auto-rollback.
Index Management
Covering Indexes
CREATE INDEX idx_orders_covering
ON orders(customer_id, created_at)
INCLUDE (total_amount, status);Partial Indexes
CREATE INDEX idx_orders_active
ON orders(created_at)
WHERE status IN ('pending', 'processing');Batch Operations
-- Bad: row-by-row
INSERT INTO products (name, price) VALUES ('A', 10);
INSERT INTO products (name, price) VALUES ('B', 15);
-- Good: batch
INSERT INTO products (name, price) VALUES ('A', 10), ('B', 15);Data Types
NVARCHARfor user-facing text,VARCHARfor system/ASCII-only data.DATETIME2overDATETIME— more precision, wider range, smaller storage.DECIMAL(p,s)for money — neverFLOATorREAL.BITfor booleans, notINTorTINYINT.- Size columns appropriately —
NVARCHAR(50)notNVARCHAR(MAX)for names. JSON(SQL 2025+) — native binary type, use overNVARCHAR(MAX)for JSON data.VECTOR(SQL 2025+) — optimized binary format for embeddings/similarity search.
SQL Server 2025 Features
Regular Expressions (prefer over complex LIKE patterns)
-- Bad: multiple LIKE patterns
WHERE Email LIKE '%@gmail.com' OR Email LIKE '%@yahoo.com'
-- Good: REGEXP_LIKE (SQL 2025+)
WHERE REGEXP_LIKE(Email, '@(gmail|yahoo)\.com$')
-- Replace substrings with regex
SELECT REGEXP_REPLACE(Phone, '[^0-9]', '') AS CleanPhone FROM Contacts
-- Extract matched substring
SELECT REGEXP_SUBSTR(Description, '\d{4}-\d{2}-\d{2}') AS ExtractedDate FROM NotesString Concatenation
-- SQL 2025+: standard || operator (alongside existing +)
SELECT FirstName || ' ' || LastName AS FullName FROM PersonJSON Aggregation
-- Bad: string manipulation to build JSON
-- Good: native JSON aggregation (SQL 2025+)
SELECT JSON_OBJECTAGG(Code VALUE Name) AS LookupMap FROM StatusType
SELECT JSON_ARRAYAGG(Name) AS NameList FROM Person WHERE IsActive = 1Fuzzy String Matching (requires PREVIEW_FEATURES)
-- Find similar names
SELECT Name, EDIT_DISTANCE_SIMILARITY(Name, 'Johnson') AS Similarity
FROM Person
WHERE EDIT_DISTANCE_SIMILARITY(Name, 'Johnson') > 70
ORDER BY Similarity DESCOther 2025 Additions
CURRENT_DATE— returns date without time (ANSI standard)SUBSTRING(expr, start)— length parameter now optionalDATEADD— number parameter now supportsbigintBASE64_ENCODE/BASE64_DECODE— binary ↔ text conversionSTRING_AGG— aggregate strings with separator (available since 2017, use it)
Performance Monitoring
-- SQL Server: top slow queries
SELECT
qs.total_elapsed_time/qs.execution_count as avg_elapsed_time,
qs.execution_count,
SUBSTRING(qt.text, (qs.statement_start_offset/2)+1,
((CASE qs.statement_end_offset WHEN -1 THEN DATALENGTH(qt.text)
ELSE qs.statement_end_offset END - qs.statement_start_offset)/2)+1) as query_text
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
ORDER BY avg_elapsed_time DESC;Review Checklist
Security
- All inputs parameterized — no string concatenation
- Dynamic SQL uses
sp_executesqlwith typed parameters - No
SELECT *on tables with sensitive columns - Appropriate permissions (least privilege)
Performance
- Indexed columns not wrapped in functions in WHERE clauses
- No unnecessary
SELECT * - JOINs use appropriate types (INNER vs LEFT vs EXISTS)
- Large result sets paginated (keyset preferred)
- No N+1 query patterns in application code
- No implicit type conversions on indexed columns
- Covering indexes for frequently-run queries
Quality
- Consistent naming (PascalCase for objects, no prefixes like
tbl_orsp_) - Schema-qualified object references (
dbo.Usersnot justUsers) SET NOCOUNT ONin stored procedures- Error handling with
TRY/CATCH+THROW(notRAISERROR) - Transactions are short and focused
SET XACT_ABORT ONin procs with transactions
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.

