SQL Pro
Core Workflow
- Schema Analysis - Review database structure, indexes, query patterns, performance bottlenecks
- Design - Create set-based operations using CTEs, window functions, appropriate joins
- Optimize - Analyze execution plans, implement covering indexes, eliminate table scans
- Verify - Run
EXPLAIN ANALYZE and confirm no sequential scans on large tables; if query does not meet sub-100ms target, iterate on index selection or query rewrite before proceeding
- Document - Provide query explanations, index rationale, performance metrics
Reference Guide
Load detailed guidance based on context:
| Topic |
Reference |
Load When |
| Query Patterns |
references/query-patterns.md |
JOINs, CTEs, subqueries, recursive queries |
| Window Functions |
references/window-functions.md |
ROW_NUMBER, RANK, LAG/LEAD, analytics |
| Optimization |
references/optimization.md |
EXPLAIN plans, indexes, statistics, tuning |
| Database Design |
references/database-design.md |
Normalization, keys, constraints, schemas |
| Dialect Differences |
references/dialect-differences.md |
PostgreSQL vs MySQL vs SQL Server specifics |
Quick-Reference Examples
CTE Pattern
-- Isolate expensive subquery logic for reuse and readability
WITH ranked_orders AS (
SELECT
customer_id,
order_id,
total_amount,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn
FROM orders
WHERE status = 'completed' -- filter early, before the join
)
SELECT customer_id, order_id, total_amount
FROM ranked_orders
WHERE rn = 1; -- latest completed order per customer
Window Function Pattern
-- Running total and rank within partition — no self-join required
SELECT
department_id,
employee_id,
salary,
SUM(salary) OVER (PARTITION BY department_id ORDER BY hire_date) AS running_payroll,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS salary_rank
FROM employees;
EXPLAIN ANALYZE Interpretation
-- PostgreSQL: always use ANALYZE to see actual row counts vs. estimates
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT *
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.created_at > NOW() - INTERVAL '30 days';
Key things to check in the output:
- Seq Scan on large table → add or fix an index
- actual rows ≫ estimated rows → run
ANALYZE <table> to refresh statistics
- Buffers: shared hit vs read → high
read count signals missing cache / index
Before / After Optimization Example
-- BEFORE: correlated subquery, one execution per row (slow)
SELECT order_id,
(SELECT SUM(quantity) FROM order_items oi WHERE oi.order_id = o.id) AS item_count
FROM orders o;
-- AFTER: single aggregation join (fast)
SELECT o.order_id, COALESCE(agg.item_count, 0) AS item_count
FROM orders o
LEFT JOIN (
SELECT order_id, SUM(quantity) AS item_count
FROM order_items
GROUP BY order_id
) agg ON agg.order_id = o.id;
-- Supporting covering index (includes all columns touched by the query)
CREATE INDEX idx_order_items_order_qty
ON order_items (order_id)
INCLUDE (quantity);
Constraints
MUST DO
- Analyze execution plans before recommending optimizations
- Use set-based operations over row-by-row processing
- Apply filtering early in query execution (before joins where possible)
- Use EXISTS over COUNT for existence checks
- Handle NULLs explicitly in comparisons and aggregations
- Create covering indexes for frequent queries
- Test with production-scale data volumes
MUST NOT DO
- Use SELECT * in production queries
- Use cursors when set-based operations work
- Ignore platform-specific optimizations when targeting a specific dialect
- Implement solutions without considering data volume and cardinality
Output Templates
When implementing SQL solutions, provide:
- Optimized query with inline comments
- Required indexes with rationale
- Execution plan analysis
- Performance metrics (before/after)
- Platform-specific notes if applicable
Documentation
1---2name: sql-pro3description: Optimizes SQL queries, designs database schemas, and troubleshoots performance issues. Use when a user asks why their query is slow, needs help writing complex joins or aggregations, mentions database performance issues, or wants to design or migrate a schema. Invoke for complex queries, window functions, CTEs, indexing strategies, query plan analysis, covering index creation, recursive queries, EXPLAIN/ANALYZE interpretation, before/after query benchmarking, or migrating queries between database dialects (PostgreSQL, MySQL, SQL Server, Oracle).4license: MIT5metadata:6 source: https://skillmd.com/skills/jeffallan/sql-pro7 author: https://github.com/Jeffallan8 version: "1.1.0"9 domain: language10 triggers: SQL optimization, query performance, database design, PostgreSQL, MySQL, SQL Server, window functions, CTEs, query tuning, EXPLAIN plan, database indexing11 role: specialist12 scope: implementation13 output-format: code14 related-skills: devops-engineer15---1617# SQL Pro1819## Core Workflow20211. **Schema Analysis** - Review database structure, indexes, query patterns, performance bottlenecks222. **Design** - Create set-based operations using CTEs, window functions, appropriate joins233. **Optimize** - Analyze execution plans, implement covering indexes, eliminate table scans244. **Verify** - Run `EXPLAIN ANALYZE` and confirm no sequential scans on large tables; if query does not meet sub-100ms target, iterate on index selection or query rewrite before proceeding255. **Document** - Provide query explanations, index rationale, performance metrics2627## Reference Guide2829Load detailed guidance based on context:3031| Topic | Reference | Load When |32|-------|-----------|-----------|33| Query Patterns | `references/query-patterns.md` | JOINs, CTEs, subqueries, recursive queries |34| Window Functions | `references/window-functions.md` | ROW_NUMBER, RANK, LAG/LEAD, analytics |35| Optimization | `references/optimization.md` | EXPLAIN plans, indexes, statistics, tuning |36| Database Design | `references/database-design.md` | Normalization, keys, constraints, schemas |37| Dialect Differences | `references/dialect-differences.md` | PostgreSQL vs MySQL vs SQL Server specifics |3839## Quick-Reference Examples4041### CTE Pattern42```sql43-- Isolate expensive subquery logic for reuse and readability44WITH ranked_orders AS (45 SELECT46 customer_id,47 order_id,48 total_amount,49 ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn50 FROM orders51 WHERE status = 'completed' -- filter early, before the join52)53SELECT customer_id, order_id, total_amount54FROM ranked_orders55WHERE rn = 1; -- latest completed order per customer56```5758### Window Function Pattern59```sql60-- Running total and rank within partition — no self-join required61SELECT62 department_id,63 employee_id,64 salary,65 SUM(salary) OVER (PARTITION BY department_id ORDER BY hire_date) AS running_payroll,66 RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS salary_rank67FROM employees;68```6970### EXPLAIN ANALYZE Interpretation71```sql72-- PostgreSQL: always use ANALYZE to see actual row counts vs. estimates73EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)74SELECT *75FROM orders o76JOIN customers c ON c.id = o.customer_id77WHERE o.created_at > NOW() - INTERVAL '30 days';78```79Key things to check in the output:80- **Seq Scan on large table** → add or fix an index81- **actual rows ≫ estimated rows** → run `ANALYZE <table>` to refresh statistics82- **Buffers: shared hit** vs **read** → high `read` count signals missing cache / index8384### Before / After Optimization Example85```sql86-- BEFORE: correlated subquery, one execution per row (slow)87SELECT order_id,88 (SELECT SUM(quantity) FROM order_items oi WHERE oi.order_id = o.id) AS item_count89FROM orders o;9091-- AFTER: single aggregation join (fast)92SELECT o.order_id, COALESCE(agg.item_count, 0) AS item_count93FROM orders o94LEFT JOIN (95 SELECT order_id, SUM(quantity) AS item_count96 FROM order_items97 GROUP BY order_id98) agg ON agg.order_id = o.id;99100-- Supporting covering index (includes all columns touched by the query)101CREATE INDEX idx_order_items_order_qty102 ON order_items (order_id)103 INCLUDE (quantity);104```105106## Constraints107108### MUST DO109- Analyze execution plans before recommending optimizations110- Use set-based operations over row-by-row processing111- Apply filtering early in query execution (before joins where possible)112- Use EXISTS over COUNT for existence checks113- Handle NULLs explicitly in comparisons and aggregations114- Create covering indexes for frequent queries115- Test with production-scale data volumes116117### MUST NOT DO118- Use SELECT * in production queries119- Use cursors when set-based operations work120- Ignore platform-specific optimizations when targeting a specific dialect121- Implement solutions without considering data volume and cardinality122123## Output Templates124125When implementing SQL solutions, provide:1261. Optimized query with inline comments1272. Required indexes with rationale1283. Execution plan analysis1294. Performance metrics (before/after)1305. Platform-specific notes if applicable131132[Documentation](https://jeffallan.github.io/claude-skills/skills/language/sql-pro/)