1
---
2
name: sql-optimization
3
description: 'Universal SQL performance optimization assistant for comprehensive query tuning, indexing strategies, and database performance analysis across all SQL databases (MySQL, PostgreSQL, SQL Server, Oracle). Provides execution plan analysis, pagination optimization, batch operations, and performance monitoring guidance.'
4
---
5
6
# SQL Performance Optimization Assistant
7
8
Expert SQL performance optimization for ${selection} (or entire project if no selection). Focus on universal SQL optimization techniques that work across MySQL, PostgreSQL, SQL Server, Oracle, and other SQL databases.
9
10
## 🎯 Core Optimization Areas
11
12
### Query Performance Analysis
13
```sql
14
-- ❌ BAD: Inefficient query patterns
15
SELECT * FROM orders o
16
WHERE YEAR(o.created_at) = 2024
17
AND o.customer_id IN (
18
SELECT c.id FROM customers c WHERE c.status = 'active'
19
);
20
21
-- ✅ GOOD: Optimized query with proper indexing hints
22
SELECT o.id, o.customer_id, o.total_amount, o.created_at
23
FROM orders o
24
INNER JOIN customers c ON o.customer_id = c.id
25
WHERE o.created_at >= '2024-01-01'
26
AND o.created_at < '2025-01-01'
27
AND c.status = 'active';
28
29
-- Required indexes:
30
-- CREATE INDEX idx_orders_created_at ON orders(created_at);
31
-- CREATE INDEX idx_customers_status ON customers(status);
32
-- CREATE INDEX idx_orders_customer_id ON orders(customer_id);
33
```
34
35
### Index Strategy Optimization
36
```sql
37
-- ❌ BAD: Poor indexing strategy
38
CREATE INDEX idx_user_data ON users(email, first_name, last_name, created_at);
39
40
-- ✅ GOOD: Optimized composite indexing
41
-- For queries filtering by email first, then sorting by created_at
42
CREATE INDEX idx_users_email_created ON users(email, created_at);
43
44
-- For full-text name searches
45
CREATE INDEX idx_users_name ON users(last_name, first_name);
46
47
-- For user status queries
48
CREATE INDEX idx_users_status_created ON users(status, created_at)
49
WHERE status IS NOT NULL;
50
```
51
52
### Subquery Optimization
53
```sql
54
-- ❌ BAD: Correlated subquery
55
SELECT p.product_name, p.price
56
FROM products p
57
WHERE p.price > (
58
SELECT AVG(price)
59
FROM products p2
60
WHERE p2.category_id = p.category_id
61
);
62
63
-- ✅ GOOD: Window function approach
64
SELECT product_name, price
65
FROM (
66
SELECT product_name, price,
67
AVG(price) OVER (PARTITION BY category_id) as avg_category_price
68
FROM products
69
) ranked
70
WHERE price > avg_category_price;
71
```
72
73
## 📊 Performance Tuning Techniques
74
75
### JOIN Optimization
76
```sql
77
-- ❌ BAD: Inefficient JOIN order and conditions
78
SELECT o.*, c.name, p.product_name
79
FROM orders o
80
LEFT JOIN customers c ON o.customer_id = c.id
81
LEFT JOIN order_items oi ON o.id = oi.order_id
82
LEFT JOIN products p ON oi.product_id = p.id
83
WHERE o.created_at > '2024-01-01'
84
AND c.status = 'active';
85
86
-- ✅ GOOD: Optimized JOIN with filtering
87
SELECT o.id, o.total_amount, c.name, p.product_name
88
FROM orders o
89
INNER JOIN customers c ON o.customer_id = c.id AND c.status = 'active'
90
INNER JOIN order_items oi ON o.id = oi.order_id
91
INNER JOIN products p ON oi.product_id = p.id
92
WHERE o.created_at > '2024-01-01';
93
```
94
95
### Pagination Optimization
96
```sql
97
-- ❌ BAD: OFFSET-based pagination (slow for large offsets)
98
SELECT * FROM products
99
ORDER BY created_at DESC
100
LIMIT 20 OFFSET 10000;
101
102
-- ✅ GOOD: Cursor-based pagination
103
SELECT * FROM products
104
WHERE created_at < '2024-06-15 10:30:00'
105
ORDER BY created_at DESC
106
LIMIT 20;
107
108
-- Or using ID-based cursor
109
SELECT * FROM products
110
WHERE id > 1000
111
ORDER BY id
112
LIMIT 20;
113
```
114
115
### Aggregation Optimization
116
```sql
117
-- ❌ BAD: Multiple separate aggregation queries
118
SELECT COUNT(*) FROM orders WHERE status = 'pending';
119
SELECT COUNT(*) FROM orders WHERE status = 'shipped';
120
SELECT COUNT(*) FROM orders WHERE status = 'delivered';
121
122
-- ✅ GOOD: Single query with conditional aggregation
123
SELECT
124
COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count,
125
COUNT(CASE WHEN status = 'shipped' THEN 1 END) as shipped_count,
126
COUNT(CASE WHEN status = 'delivered' THEN 1 END) as delivered_count
127
FROM orders;
128
```
129
130
## 🔍 Query Anti-Patterns
131
132
### SELECT Performance Issues
133
```sql
134
-- ❌ BAD: SELECT * anti-pattern
135
SELECT * FROM large_table lt
136
JOIN another_table at ON lt.id = at.ref_id;
137
138
-- ✅ GOOD: Explicit column selection
139
SELECT lt.id, lt.name, at.value
140
FROM large_table lt
141
JOIN another_table at ON lt.id = at.ref_id;
142
```
143
144
### WHERE Clause Optimization
145
```sql
146
-- ❌ BAD: Function calls in WHERE clause
147
SELECT * FROM orders
148
WHERE UPPER(customer_email) = 'JOHN@EXAMPLE.COM';
149
150
-- ✅ GOOD: Index-friendly WHERE clause
151
SELECT * FROM orders
152
WHERE customer_email = 'john@example.com';
153
-- Consider: CREATE INDEX idx_orders_email ON orders(LOWER(customer_email));
154
```
155
156
### OR vs UNION Optimization
157
```sql
158
-- ❌ BAD: Complex OR conditions
159
SELECT * FROM products
160
WHERE (category = 'electronics' AND price < 1000)
161
OR (category = 'books' AND price < 50);
162
163
-- ✅ GOOD: UNION approach for better optimization
164
SELECT * FROM products WHERE category = 'electronics' AND price < 1000
165
UNION ALL
166
SELECT * FROM products WHERE category = 'books' AND price < 50;
167
```
168
169
## 📈 Database-Agnostic Optimization
170
171
### Batch Operations
172
```sql
173
-- ❌ BAD: Row-by-row operations
174
INSERT INTO products (name, price) VALUES ('Product 1', 10.00);
175
INSERT INTO products (name, price) VALUES ('Product 2', 15.00);
176
INSERT INTO products (name, price) VALUES ('Product 3', 20.00);
177
178
-- ✅ GOOD: Batch insert
179
INSERT INTO products (name, price) VALUES
180
('Product 1', 10.00),
181
('Product 2', 15.00),
182
('Product 3', 20.00);
183
```
184
185
### Temporary Table Usage
186
```sql
187
-- ✅ GOOD: Using temporary tables for complex operations
188
CREATE TEMPORARY TABLE temp_calculations AS
189
SELECT customer_id,
190
SUM(total_amount) as total_spent,
191
COUNT(*) as order_count
192
FROM orders
193
WHERE created_at >= '2024-01-01'
194
GROUP BY customer_id;
195
196
-- Use the temp table for further calculations
197
SELECT c.name, tc.total_spent, tc.order_count
198
FROM temp_calculations tc
199
JOIN customers c ON tc.customer_id = c.id
200
WHERE tc.total_spent > 1000;
201
```
202
203
## 🛠️ Index Management
204
205
### Index Design Principles
206
```sql
207
-- ✅ GOOD: Covering index design
208
CREATE INDEX idx_orders_covering
209
ON orders(customer_id, created_at)
210
INCLUDE (total_amount, status); -- SQL Server syntax
211
-- Or: CREATE INDEX idx_orders_covering ON orders(customer_id, created_at, total_amount, status); -- Other databases
212
```
213
214
### Partial Index Strategy
215
```sql
216
-- ✅ GOOD: Partial indexes for specific conditions
217
CREATE INDEX idx_orders_active
218
ON orders(created_at)
219
WHERE status IN ('pending', 'processing');
220
```
221
222
## 📊 Performance Monitoring Queries
223
224
### Query Performance Analysis
225
```sql
226
-- Generic approach to identify slow queries
227
-- (Specific syntax varies by database)
228
229
-- For MySQL:
230
SELECT query_time, lock_time, rows_sent, rows_examined, sql_text
231
FROM mysql.slow_log
232
ORDER BY query_time DESC;
233
234
-- For PostgreSQL:
235
SELECT query, calls, total_time, mean_time
236
FROM pg_stat_statements
237
ORDER BY total_time DESC;
238
239
-- For SQL Server:
240
SELECT
241
qs.total_elapsed_time/qs.execution_count as avg_elapsed_time,
242
qs.execution_count,
243
SUBSTRING(qt.text, (qs.statement_start_offset/2)+1,
244
((CASE qs.statement_end_offset WHEN -1 THEN DATALENGTH(qt.text)
245
ELSE qs.statement_end_offset END - qs.statement_start_offset)/2)+1) as query_text
246
FROM sys.dm_exec_query_stats qs
247
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
248
ORDER BY avg_elapsed_time DESC;
249
```
250
251
## 🎯 Universal Optimization Checklist
252
253
### Query Structure
254
- [ ] Avoiding SELECT * in production queries
255
- [ ] Using appropriate JOIN types (INNER vs LEFT/RIGHT)
256
- [ ] Filtering early in WHERE clauses
257
- [ ] Using EXISTS instead of IN for subqueries when appropriate
258
- [ ] Avoiding functions in WHERE clauses that prevent index usage
259
260
### Index Strategy
261
- [ ] Creating indexes on frequently queried columns
262
- [ ] Using composite indexes in the right column order
263
- [ ] Avoiding over-indexing (impacts INSERT/UPDATE performance)
264
- [ ] Using covering indexes where beneficial
265
- [ ] Creating partial indexes for specific query patterns
266
267
### Data Types and Schema
268
- [ ] Using appropriate data types for storage efficiency
269
- [ ] Normalizing appropriately (3NF for OLTP, denormalized for OLAP)
270
- [ ] Using constraints to help query optimizer
271
- [ ] Partitioning large tables when appropriate
272
273
### Query Patterns
274
- [ ] Using LIMIT/TOP for result set control
275
- [ ] Implementing efficient pagination strategies
276
- [ ] Using batch operations for bulk data changes
277
- [ ] Avoiding N+1 query problems
278
- [ ] Using prepared statements for repeated queries
279
280
### Performance Testing
281
- [ ] Testing queries with realistic data volumes
282
- [ ] Analyzing query execution plans
283
- [ ] Monitoring query performance over time
284
- [ ] Setting up alerts for slow queries
285
- [ ] Regular index usage analysis
286
287
## 📝 Optimization Methodology
288
289
1. **Identify**: Use database-specific tools to find slow queries
290
2. **Analyze**: Examine execution plans and identify bottlenecks
291
3. **Optimize**: Apply appropriate optimization techniques
292
4. **Test**: Verify performance improvements
293
5. **Monitor**: Continuously track performance metrics
294
6. **Iterate**: Regular performance review and optimization
295
296
Focus on measurable performance improvements and always test optimizations with realistic data volumes and query patterns.
297