-- Bad: Using SELECT * SELECT*FROM users WHERE id =1;
-- Good: Select only needed columns SELECT id, name, email FROM users WHERE id =1;
-- Bad: Using OR with different columns SELECT*FROM products WHERE category ='electronics'OR price <100;
-- Good: Use UNION for OR conditions on different columns SELECT*FROM products WHERE category ='electronics' UNION SELECT*FROM products WHERE price <100;
-- Use EXPLAIN to analyze queries EXPLAIN ANALYZE SELECT u.name, COUNT(o.id) as order_count FROM users u LEFTJOIN orders o ON u.id = o.user_id GROUPBY u.id, u.name;
Avoiding N+1 Queries
Use eager loading to prevent N+1 problems:
1 2 3 4 5 6 7 8 9 10 11
# Bad: N+1 query problem users = User.query.all() for user in users: print(user.orders) # Separate query for each user
# Good: Eager loading from sqlalchemy.orm import joinedload
users = User.query.options(joinedload(User.orders)).all() for user in users: print(user.orders) # No additional queries
defget_user(user_id): # Try cache first cache_key = f'user:{user_id}' cached = redis_client.get(cache_key) if cached: return json.loads(cached) # Query database if not in cache user = db.query(User).filter(User.id == user_id).first() # Store in cache for 1 hour redis_client.setex( cache_key, 3600, json.dumps(user.to_dict()) ) return user
Batch Operations
Process multiple records efficiently:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
-- Bad: Multiple individual inserts INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com'); INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com'); INSERT INTO users (name, email) VALUES ('Charlie', 'charlie@example.com');