---
name: database
description: Database design, SQL optimization, ORM patterns, migrations. Use for database-related development tasks.
---

# Database Skill

## Schema Design Principles
- Use meaningful table and column names
- Always have a primary key (prefer UUID or auto-increment)
- Add created_at/updated_at timestamps
- Use foreign keys for referential integrity
- Index columns used in WHERE, JOIN, ORDER BY

## SQL Best Practices
```sql
-- Use parameterized queries (NEVER concatenate)
SELECT * FROM users WHERE email = $1;

-- Pagination
SELECT * FROM posts ORDER BY created_at DESC LIMIT 20 OFFSET 40;

-- Efficient joins
SELECT u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name
HAVING COUNT(o.id) > 5;
```

## Migration Strategy
1. Always write reversible migrations
2. Test migrations on a copy first
3. Never modify released migrations
4. Use meaningful migration names

```bash
# Alembic (Python)
alembic revision --autogenerate -m "add_users_table"
alembic upgrade head
alembic downgrade -1
```

## Common ORM Patterns
```python
# SQLAlchemy example
class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    email = Column(String, unique=True, nullable=False, index=True)
    created_at = Column(DateTime, default=func.now())
    posts = relationship("Post", back_populates="author")
```
