SQL Code Review

SQL Code Review

Reviews SQL code across MySQL, PostgreSQL, SQL Server and Oracle for injection risks, access control, performance, maintainability and anti-patterns.

Skill files1 file
SKILL.md302 lines
1
---
2
name: sql-code-review
3
description: 'Universal SQL code review assistant that performs comprehensive security, maintainability, and code quality analysis across all SQL databases (MySQL, PostgreSQL, SQL Server, Oracle). Focuses on SQL injection prevention, access control, code standards, and anti-pattern detection. Complements SQL optimization prompt for complete development coverage.'
4
---
5
6
# SQL Code Review
7
8
Perform a thorough SQL code review of ${selection} (or entire project if no selection) focusing on security, performance, maintainability, and database best practices.
9
10
## 🔒 Security Analysis
11
12
### SQL Injection Prevention
13
```sql
14
-- ❌ CRITICAL: SQL Injection vulnerability
15
query = "SELECT * FROM users WHERE id = " + userInput;
16
query = f"DELETE FROM orders WHERE user_id = {user_id}";
17
18
-- ✅ SECURE: Parameterized queries
19
-- PostgreSQL/MySQL
20
PREPARE stmt FROM 'SELECT * FROM users WHERE id = ?';
21
EXECUTE stmt USING @user_id;
22
23
-- SQL Server
24
EXEC sp_executesql N'SELECT * FROM users WHERE id = @id', N'@id INT', @id = @user_id;
25
```
26
27
### Access Control & Permissions
28
- **Principle of Least Privilege**: Grant minimum required permissions
29
- **Role-Based Access**: Use database roles instead of direct user permissions
30
- **Schema Security**: Proper schema ownership and access controls
31
- **Function/Procedure Security**: Review DEFINER vs INVOKER rights
32
33
### Data Protection
34
- **Sensitive Data Exposure**: Avoid SELECT * on tables with sensitive columns
35
- **Audit Logging**: Ensure sensitive operations are logged
36
- **Data Masking**: Use views or functions to mask sensitive data
37
- **Encryption**: Verify encrypted storage for sensitive data
38
39
## ⚡ Performance Optimization
40
41
### Query Structure Analysis
42
```sql
43
-- ❌ BAD: Inefficient query patterns
44
SELECT DISTINCT u.*
45
FROM users u, orders o, products p
46
WHERE u.id = o.user_id
47
AND o.product_id = p.id
48
AND YEAR(o.order_date) = 2024;
49
50
-- ✅ GOOD: Optimized structure
51
SELECT u.id, u.name, u.email
52
FROM users u
53
INNER JOIN orders o ON u.id = o.user_id
54
WHERE o.order_date >= '2024-01-01'
55
AND o.order_date < '2025-01-01';
56
```
57
58
### Index Strategy Review
59
- **Missing Indexes**: Identify columns that need indexing
60
- **Over-Indexing**: Find unused or redundant indexes
61
- **Composite Indexes**: Multi-column indexes for complex queries
62
- **Index Maintenance**: Check for fragmented or outdated indexes
63
64
### Join Optimization
65
- **Join Types**: Verify appropriate join types (INNER vs LEFT vs EXISTS)
66
- **Join Order**: Optimize for smaller result sets first
67
- **Cartesian Products**: Identify and fix missing join conditions
68
- **Subquery vs JOIN**: Choose the most efficient approach
69
70
### Aggregate and Window Functions
71
```sql
72
-- ❌ BAD: Inefficient aggregation
73
SELECT user_id,
74
(SELECT COUNT(*) FROM orders o2 WHERE o2.user_id = o1.user_id) as order_count
75
FROM orders o1
76
GROUP BY user_id;
77
78
-- ✅ GOOD: Efficient aggregation
79
SELECT user_id, COUNT(*) as order_count
80
FROM orders
81
GROUP BY user_id;
82
```
83
84
## 🛠️ Code Quality & Maintainability
85
86
### SQL Style & Formatting
87
```sql
88
-- ❌ BAD: Poor formatting and style
89
select u.id,u.name,o.total from users u left join orders o on u.id=o.user_id where u.status='active' and o.order_date>='2024-01-01';
90
91
-- ✅ GOOD: Clean, readable formatting
92
SELECT u.id,
93
u.name,
94
o.total
95
FROM users u
96
LEFT JOIN orders o ON u.id = o.user_id
97
WHERE u.status = 'active'
98
AND o.order_date >= '2024-01-01';
99
```
100
101
### Naming Conventions
102
- **Consistent Naming**: Tables, columns, constraints follow consistent patterns
103
- **Descriptive Names**: Clear, meaningful names for database objects
104
- **Reserved Words**: Avoid using database reserved words as identifiers
105
- **Case Sensitivity**: Consistent case usage across schema
106
107
### Schema Design Review
108
- **Normalization**: Appropriate normalization level (avoid over/under-normalization)
109
- **Data Types**: Optimal data type choices for storage and performance
110
- **Constraints**: Proper use of PRIMARY KEY, FOREIGN KEY, CHECK, NOT NULL
111
- **Default Values**: Appropriate default values for columns
112
113
## 🗄️ Database-Specific Best Practices
114
115
### PostgreSQL
116
```sql
117
-- Use JSONB for JSON data
118
CREATE TABLE events (
119
id SERIAL PRIMARY KEY,
120
data JSONB NOT NULL,
121
created_at TIMESTAMPTZ DEFAULT NOW()
122
);
123
124
-- GIN index for JSONB queries
125
CREATE INDEX idx_events_data ON events USING gin(data);
126
127
-- Array types for multi-value columns
128
CREATE TABLE tags (
129
post_id INT,
130
tag_names TEXT[]
131
);
132
```
133
134
### MySQL
135
```sql
136
-- Use appropriate storage engines
137
CREATE TABLE sessions (
138
id VARCHAR(128) PRIMARY KEY,
139
data TEXT,
140
expires TIMESTAMP
141
) ENGINE=InnoDB;
142
143
-- Optimize for InnoDB
144
ALTER TABLE large_table
145
ADD INDEX idx_covering (status, created_at, id);
146
```
147
148
### SQL Server
149
```sql
150
-- Use appropriate data types
151
CREATE TABLE products (
152
id BIGINT IDENTITY(1,1) PRIMARY KEY,
153
name NVARCHAR(255) NOT NULL,
154
price DECIMAL(10,2) NOT NULL,
155
created_at DATETIME2 DEFAULT GETUTCDATE()
156
);
157
158
-- Columnstore indexes for analytics
159
CREATE COLUMNSTORE INDEX idx_sales_cs ON sales;
160
```
161
162
### Oracle
163
```sql
164
-- Use sequences for auto-increment
165
CREATE SEQUENCE user_id_seq START WITH 1 INCREMENT BY 1;
166
167
CREATE TABLE users (
168
id NUMBER DEFAULT user_id_seq.NEXTVAL PRIMARY KEY,
169
name VARCHAR2(255) NOT NULL
170
);
171
```
172
173
## 🧪 Testing & Validation
174
175
### Data Integrity Checks
176
```sql
177
-- Verify referential integrity
178
SELECT o.user_id
179
FROM orders o
180
LEFT JOIN users u ON o.user_id = u.id
181
WHERE u.id IS NULL;
182
183
-- Check for data consistency
184
SELECT COUNT(*) as inconsistent_records
185
FROM products
186
WHERE price < 0 OR stock_quantity < 0;
187
```
188
189
### Performance Testing
190
- **Execution Plans**: Review query execution plans
191
- **Load Testing**: Test queries with realistic data volumes
192
- **Stress Testing**: Verify performance under concurrent load
193
- **Regression Testing**: Ensure optimizations don't break functionality
194
195
## 📊 Common Anti-Patterns
196
197
### N+1 Query Problem
198
```sql
199
-- ❌ BAD: N+1 queries in application code
200
for user in users:
201
orders = query("SELECT * FROM orders WHERE user_id = ?", user.id)
202
203
-- ✅ GOOD: Single optimized query
204
SELECT u.*, o.*
205
FROM users u
206
LEFT JOIN orders o ON u.id = o.user_id;
207
```
208
209
### Overuse of DISTINCT
210
```sql
211
-- ❌ BAD: DISTINCT masking join issues
212
SELECT DISTINCT u.name
213
FROM users u, orders o
214
WHERE u.id = o.user_id;
215
216
-- ✅ GOOD: Proper join without DISTINCT
217
SELECT u.name
218
FROM users u
219
INNER JOIN orders o ON u.id = o.user_id
220
GROUP BY u.name;
221
```
222
223
### Function Misuse in WHERE Clauses
224
```sql
225
-- ❌ BAD: Functions prevent index usage
226
SELECT * FROM orders
227
WHERE YEAR(order_date) = 2024;
228
229
-- ✅ GOOD: Range conditions use indexes
230
SELECT * FROM orders
231
WHERE order_date >= '2024-01-01'
232
AND order_date < '2025-01-01';
233
```
234
235
## 📋 SQL Review Checklist
236
237
### Security
238
- [ ] All user inputs are parameterized
239
- [ ] No dynamic SQL construction with string concatenation
240
- [ ] Appropriate access controls and permissions
241
- [ ] Sensitive data is properly protected
242
- [ ] SQL injection attack vectors are eliminated
243
244
### Performance
245
- [ ] Indexes exist for frequently queried columns
246
- [ ] No unnecessary SELECT * statements
247
- [ ] JOINs are optimized and use appropriate types
248
- [ ] WHERE clauses are selective and use indexes
249
- [ ] Subqueries are optimized or converted to JOINs
250
251
### Code Quality
252
- [ ] Consistent naming conventions
253
- [ ] Proper formatting and indentation
254
- [ ] Meaningful comments for complex logic
255
- [ ] Appropriate data types are used
256
- [ ] Error handling is implemented
257
258
### Schema Design
259
- [ ] Tables are properly normalized
260
- [ ] Constraints enforce data integrity
261
- [ ] Indexes support query patterns
262
- [ ] Foreign key relationships are defined
263
- [ ] Default values are appropriate
264
265
## 🎯 Review Output Format
266
267
### Issue Template
268
````
269
## [PRIORITY] [CATEGORY]: [Brief Description]
270
271
**Location**: [Table/View/Procedure name and line number if applicable]
272
**Issue**: [Detailed explanation of the problem]
273
**Security Risk**: [If applicable - injection risk, data exposure, etc.]
274
**Performance Impact**: [Query cost, execution time impact]
275
**Recommendation**: [Specific fix with code example]
276
277
**Before**:
278
```sql
279
-- Problematic SQL
280
```
281
282
**After**:
283
```sql
284
-- Improved SQL
285
```
286
287
**Expected Improvement**: [Performance gain, security benefit]
288
````
289
290
### Summary Assessment
291
- **Security Score**: [1-10] - SQL injection protection, access controls
292
- **Performance Score**: [1-10] - Query efficiency, index usage
293
- **Maintainability Score**: [1-10] - Code quality, documentation
294
- **Schema Quality Score**: [1-10] - Design patterns, normalization
295
296
### Top 3 Priority Actions
297
1. **[Critical Security Fix]**: Address SQL injection vulnerabilities
298
2. **[Performance Optimization]**: Add missing indexes or optimize queries
299
3. **[Code Quality]**: Improve naming conventions and documentation
300
301
Focus on providing actionable, database-agnostic recommendations while highlighting platform-specific optimizations and best practices.
302

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…