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
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
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). Use when this capability is needed.4---56# SQL Pro78## Core Workflow9101. **Schema Analysis** - Review database structure, indexes, query patterns, performance bottlenecks112. **Design** - Create set-based operations using CTEs, window functions, appropriate joins123. **Optimize** - Analyze execution plans, implement covering indexes, eliminate table scans134. **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 proceeding145. **Document** - Provide query explanations, index rationale, performance metrics1516## Reference Guide1718Load detailed guidance based on context:1920| Topic | Reference | Load When |21|-------|-----------|-----------|22| Query Patterns | `references/query-patterns.md` | JOINs, CTEs, subqueries, recursive queries |23| Window Functions | `references/window-functions.md` | ROW_NUMBER, RANK, LAG/LEAD, analytics |24| Optimization | `references/optimization.md` | EXPLAIN plans, indexes, statistics, tuning |25| Database Design | `references/database-design.md` | Normalization, keys, constraints, schemas |26| Dialect Differences | `references/dialect-differences.md` | PostgreSQL vs MySQL vs SQL Server specifics |2728## Quick-Reference Examples2930### CTE Pattern31```sql32-- Isolate expensive subquery logic for reuse and readability33WITH ranked_orders AS (34 SELECT35 customer_id,36 order_id,37 total_amount,38 ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn39 FROM orders40 WHERE status = 'completed' -- filter early, before the join41)42SELECT customer_id, order_id, total_amount43FROM ranked_orders44WHERE rn = 1; -- latest completed order per customer45```4647### Window Function Pattern48```sql49-- Running total and rank within partition — no self-join required50SELECT51 department_id,52 employee_id,53 salary,54 SUM(salary) OVER (PARTITION BY department_id ORDER BY hire_date) AS running_payroll,55 RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS salary_rank56FROM employees;57```5859### EXPLAIN ANALYZE Interpretation60```sql61-- PostgreSQL: always use ANALYZE to see actual row counts vs. estimates62EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)63SELECT *64FROM orders o65JOIN customers c ON c.id = o.customer_id66WHERE o.created_at > NOW() - INTERVAL '30 days';67```68Key things to check in the output:69- **Seq Scan on large table** → add or fix an index70- **actual rows ≫ estimated rows** → run `ANALYZE <table>` to refresh statistics71- **Buffers: shared hit** vs **read** → high `read` count signals missing cache / index7273### Before / After Optimization Example74```sql75-- BEFORE: correlated subquery, one execution per row (slow)76SELECT order_id,77 (SELECT SUM(quantity) FROM order_items oi WHERE oi.order_id = o.id) AS item_count78FROM orders o;7980-- AFTER: single aggregation join (fast)81SELECT o.order_id, COALESCE(agg.item_count, 0) AS item_count82FROM orders o83LEFT JOIN (84 SELECT order_id, SUM(quantity) AS item_count85 FROM order_items86 GROUP BY order_id87) agg ON agg.order_id = o.id;8889-- Supporting covering index (includes all columns touched by the query)90CREATE INDEX idx_order_items_order_qty91 ON order_items (order_id)92 INCLUDE (quantity);93```9495## Constraints9697### MUST DO98- Analyze execution plans before recommending optimizations99- Use set-based operations over row-by-row processing100- Apply filtering early in query execution (before joins where possible)101- Use EXISTS over COUNT for existence checks102- Handle NULLs explicitly in comparisons and aggregations103- Create covering indexes for frequent queries104- Test with production-scale data volumes105106### MUST NOT DO107- Use SELECT * in production queries108- Use cursors when set-based operations work109- Ignore platform-specific optimizations when targeting a specific dialect110- Implement solutions without considering data volume and cardinality111112## Output Templates113114When implementing SQL solutions, provide:1151. Optimized query with inline comments1162. Required indexes with rationale1173. Execution plan analysis1184. Performance metrics (before/after)1195. Platform-specific notes if applicable120121---122> Converted and distributed by [TomeVault](https://tomevault.io/claim/jeffallan) — claim your Tome and manage your conversions.123<!-- tomevault:4.0:skill_md:2026-04-11 -->