[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M799F2E78M2K2M4DR17TD548":3,"skill-same:01M799F2E78M2K2M4DR17TD548":44},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":29,"install":30,"resources":43},"01M799F2E78M2K2M4DR17TD548","Database Design",null,"Comprehensive database design patterns for relational, document, and hybrid architectures. Covers ER diagrams, normalization, indexing, partitioning, and schema migrations. Use when designing schemas, optimizing queries, planning data models, or choosing between SQL\u002FNoSQL architectures.","pjherron\u002Fhypoc","pjherron","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F800763?v=4","01M799C7XC0XKKW2D6RMYNHCY8","Patrick Herron","01M799C7XZPGZ9QZ7XAQN5MQAN",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fpjherron\u002Fhypoc\u002Fblob\u002Fmain\u002Fhypoc\u002Fskills\u002Fdatabase-design\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: \"Database Design\"\ndescription: \"Comprehensive database design patterns for relational, document, and hybrid architectures. Covers ER diagrams, normalization, indexing, partitioning, and schema migrations. Use when designing schemas, optimizing queries, planning data models, or choosing between SQL\u002FNoSQL architectures.\"\n---\n\n# Database Design\n\n## What This Skill Does\n\nProvides production-ready database design patterns including ER modeling, normalization strategies, index optimization, multi-database architectures, and schema evolution. Covers relational (Postgres\u002FMySQL), document (MongoDB), time-series, and graph data models.\n\n## Prerequisites\n\n- Understanding of relational database concepts\n- Familiarity with at least one database system (Postgres, MySQL, MongoDB)\n- Knowledge of SQL or NoSQL query languages\n\n---\n\n## Quick Start\n\n### Choose Your Database Type\n\n```\nStructured, relational data → Postgres\u002FMySQL\nFlexible schemas, nested docs → MongoDB\nTime-series metrics → TimescaleDB\u002FInfluxDB\nGraph relationships → Neo4j\nMulti-model needs → Postgres + Redis + ElasticSearch\n```\n\n### Basic Design Workflow\n\n1. **Identify entities** → Users, Orders, Products\n2. **Define relationships** → One-to-many, many-to-many\n3. **Normalize to 3NF** → Remove redundancy\n4. **Add indexes** → For common queries\n5. **Plan migrations** → Version schema changes\n\n---\n\n## ER Diagram Design\n\n### Entity-Relationship Fundamentals\n\n**Entities**: Nouns in your domain (User, Order, Product)\n**Attributes**: Properties of entities (name, email, price)\n**Relationships**: Associations between entities (User places Order)\n\n### Relationship Types\n\n#### One-to-Many (1:N)\n\n```\nUser ──\u003C Order\n 1       N\n\nUser (1)               Order (N)\n────────              ──────────\nid (PK)               id (PK)\nemail                 user_id (FK)\nname                  total\n                      created_at\n```\n\n**Implementation**:\n```sql\nCREATE TABLE users (\n  id SERIAL PRIMARY KEY,\n  email VARCHAR(255) UNIQUE NOT NULL,\n  name VARCHAR(100) NOT NULL\n);\n\nCREATE TABLE orders (\n  id SERIAL PRIMARY KEY,\n  user_id INTEGER NOT NULL REFERENCES users(id),\n  total DECIMAL(10,2) NOT NULL,\n  created_at TIMESTAMP DEFAULT NOW()\n);\n\nCREATE INDEX idx_orders_user_id ON orders(user_id);\n```\n\n#### Many-to-Many (N:M)\n\n```\nStudent ──>\u003C Course\n   N         M\n\nStudent          Enrollment         Course\n────────        ────────────        ────────\nid (PK)         student_id (FK)     id (PK)\nname            course_id (FK)      name\n                grade               credits\n                enrolled_at\n```\n\n**Implementation**:\n```sql\nCREATE TABLE students (\n  id SERIAL PRIMARY KEY,\n  name VARCHAR(100) NOT NULL\n);\n\nCREATE TABLE courses (\n  id SERIAL PRIMARY KEY,\n  name VARCHAR(100) NOT NULL,\n  credits INTEGER NOT NULL\n);\n\n-- Junction\u002Fjoin table\nCREATE TABLE enrollments (\n  student_id INTEGER NOT NULL REFERENCES students(id),\n  course_id INTEGER NOT NULL REFERENCES courses(id),\n  grade VARCHAR(2),\n  enrolled_at TIMESTAMP DEFAULT NOW(),\n  PRIMARY KEY (student_id, course_id)\n);\n\nCREATE INDEX idx_enrollments_student ON enrollments(student_id);\nCREATE INDEX idx_enrollments_course ON enrollments(course_id);\n```\n\n#### One-to-One (1:1)\n\n```\nUser ── UserProfile\n 1        1\n\nUser                 UserProfile\n────────            ──────────────\nid (PK)             user_id (PK, FK)\nemail               bio\n                    avatar_url\n                    preferences\n```\n\n**When to Use**: Separate sensitive data, optional extensions, performance optimization.\n\n**Implementation**:\n```sql\nCREATE TABLE users (\n  id SERIAL PRIMARY KEY,\n  email VARCHAR(255) UNIQUE NOT NULL\n);\n\nCREATE TABLE user_profiles (\n  user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,\n  bio TEXT,\n  avatar_url VARCHAR(500),\n  preferences JSONB\n);\n```\n\n### Self-Referencing Relationships\n\n**Use Case**: Hierarchies, trees, graphs\n\n```\nEmployee ──\u003C Employee (manager)\n\nEmployee\n────────────────\nid (PK)\nname\nmanager_id (FK) → employees(id)\n```\n\n**Implementation**:\n```sql\nCREATE TABLE employees (\n  id SERIAL PRIMARY KEY,\n  name VARCHAR(100) NOT NULL,\n  manager_id INTEGER REFERENCES employees(id),\n  CONSTRAINT no_self_reference CHECK (id != manager_id)\n);\n\nCREATE INDEX idx_employees_manager ON employees(manager_id);\n\n-- Query: Find all direct reports\nSELECT * FROM employees WHERE manager_id = 5;\n\n-- Query: Find entire reporting chain (recursive CTE)\nWITH RECURSIVE reporting_chain AS (\n  SELECT id, name, manager_id, 1 AS level\n  FROM employees\n  WHERE id = 5\n  \n  UNION ALL\n  \n  SELECT e.id, e.name, e.manager_id, rc.level + 1\n  FROM employees e\n  JOIN reporting_chain rc ON e.manager_id = rc.id\n)\nSELECT * FROM reporting_chain ORDER BY level;\n```\n\n---\n\n## Database Normalization\n\n### First Normal Form (1NF)\n\n**Rule**: Eliminate repeating groups, ensure atomic values.\n\n```\n❌ BAD: Non-atomic values\nUser\n─────────────────────────\nid | name  | phone_numbers\n─────────────────────────\n1  | Alice | 555-1234, 555-5678\n\n✅ GOOD: Atomic values, separate table\nUser                     Phone\n────────────────        ────────────────────\nid | name               user_id | number\n────────────────        ────────────────────\n1  | Alice              1       | 555-1234\n                        1       | 555-5678\n```\n\n### Second Normal Form (2NF)\n\n**Rule**: Meet 1NF + no partial dependencies (all non-key attributes depend on entire primary key).\n\n```\n❌ BAD: Partial dependency\nOrderItem (composite key: order_id, product_id)\n─────────────────────────────────────────────\norder_id | product_id | product_name | quantity\n─────────────────────────────────────────────\n1        | 10         | Widget       | 5\n1        | 20         | Gadget       | 3\n\nproduct_name depends only on product_id (partial dependency)\n\n✅ GOOD: Remove partial dependencies\nOrderItem                        Product\n────────────────────────        ─────────────────\norder_id | product_id | qty     id | name\n────────────────────────        ─────────────────\n1        | 10         | 5       10 | Widget\n1        | 20         | 3       20 | Gadget\n```\n\n### Third Normal Form (3NF)\n\n**Rule**: Meet 2NF + no transitive dependencies.\n\n```\n❌ BAD: Transitive dependency\nEmployee\n────────────────────────────────────────────\nid | name  | dept_id | dept_name | dept_location\n────────────────────────────────────────────\n1  | Alice | 5       | Sales     | New York\n2  | Bob   | 5       | Sales     | New York\n\ndept_name and dept_location depend on dept_id (transitive)\n\n✅ GOOD: Remove transitive dependencies\nEmployee                    Department\n─────────────────          ────────────────────────\nid | name  | dept_id       id | name  | location\n─────────────────          ────────────────────────\n1  | Alice | 5             5  | Sales | New York\n2  | Bob   | 5\n```\n\n### Boyce-Codd Normal Form (BCNF)\n\n**Rule**: Meet 3NF + every determinant is a candidate key.\n\n```\n❌ BAD: Violates BCNF\nCourseProfessor\n────────────────────────────────\nstudent_id | course | professor\n────────────────────────────────\n1          | Math   | Dr. Smith\n2          | Math   | Dr. Smith\n\nAssumption: Each course has only one professor.\nprofessor → course (professor determines course)\nBut professor is not a candidate key.\n\n✅ GOOD: Split into two tables\nStudentCourse              CourseProfessor\n───────────────           ──────────────────\nstudent_id | course       course | professor\n───────────────           ──────────────────\n1          | Math         Math   | Dr. Smith\n2          | Math\n```\n\n---\n\n## When to Denormalize\n\n### Performance Tradeoffs\n\n**Normalize When**:\n- Write-heavy workloads (avoid update anomalies)\n- Storage is expensive\n- Data integrity is critical\n- Schema is stable\n\n**Denormalize When**:\n- Read-heavy workloads (reduce joins)\n- Query performance is critical\n- Aggregations are frequent\n- Data is mostly immutable\n\n### Common Denormalization Patterns\n\n#### Pattern 1: Aggregate Caching\n\n```sql\n-- Normalized\nSELECT COUNT(*) FROM orders WHERE user_id = 123;\n\n-- Denormalized: Cache count in users table\nCREATE TABLE users (\n  id SERIAL PRIMARY KEY,\n  email VARCHAR(255),\n  order_count INTEGER DEFAULT 0  -- Cached aggregate\n);\n\n-- Update via trigger\nCREATE OR REPLACE FUNCTION update_order_count()\nRETURNS TRIGGER AS $$\nBEGIN\n  UPDATE users\n  SET order_count = (SELECT COUNT(*) FROM orders WHERE user_id = NEW.user_id)\n  WHERE id = NEW.user_id;\n  RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE TRIGGER trg_update_order_count\nAFTER INSERT OR DELETE ON orders\nFOR EACH ROW EXECUTE FUNCTION update_order_count();\n```\n\n#### Pattern 2: Flattening Joins\n\n```sql\n-- Normalized: Requires join\nSELECT o.id, o.total, u.name, u.email\nFROM orders o\nJOIN users u ON o.user_id = u.id;\n\n-- Denormalized: Embed user info\nCREATE TABLE orders (\n  id SERIAL PRIMARY KEY,\n  user_id INTEGER REFERENCES users(id),\n  user_name VARCHAR(100),    -- Denormalized\n  user_email VARCHAR(255),   -- Denormalized\n  total DECIMAL(10,2)\n);\n\n-- Trade-off: Faster reads, slower writes, potential inconsistency\n```\n\n#### Pattern 3: Materialized Views\n\n```sql\n-- Create pre-computed view\nCREATE MATERIALIZED VIEW order_summaries AS\nSELECT\n  user_id,\n  COUNT(*) AS order_count,\n  SUM(total) AS lifetime_value,\n  MAX(created_at) AS last_order_date\nFROM orders\nGROUP BY user_id;\n\nCREATE INDEX idx_order_summaries_user ON order_summaries(user_id);\n\n-- Refresh periodically\nREFRESH MATERIALIZED VIEW CONCURRENTLY order_summaries;\n```\n\n---\n\n## Index Design Strategies\n\n### Index Types\n\n#### B-Tree Index (Default)\n\n**Use For**: Equality, range queries, sorting\n\n```sql\nCREATE INDEX idx_users_email ON users(email);\nCREATE INDEX idx_orders_created ON orders(created_at);\n\n-- Efficient queries\nSELECT * FROM users WHERE email = 'alice@example.com';\nSELECT * FROM orders WHERE created_at >= '2025-01-01';\nSELECT * FROM orders ORDER BY created_at DESC LIMIT 10;\n```\n\n#### Unique Index\n\n```sql\nCREATE UNIQUE INDEX idx_users_email_unique ON users(email);\n\n-- Enforces uniqueness, faster than CHECK constraint\n```\n\n#### Partial Index\n\n**Use For**: Indexing subset of rows\n\n```sql\n-- Index only active orders (reduces index size)\nCREATE INDEX idx_orders_active ON orders(user_id)\nWHERE status = 'active';\n\n-- Efficient for: WHERE user_id = X AND status = 'active'\n-- Ignored for: WHERE user_id = X AND status = 'completed'\n```\n\n#### Composite Index\n\n**Rule**: Order matters! Most selective columns first.\n\n```sql\n-- Good for: WHERE user_id = X AND status = Y\nCREATE INDEX idx_orders_user_status ON orders(user_id, status);\n\n-- Also good for: WHERE user_id = X (left prefix)\n-- NOT good for: WHERE status = Y (right side only)\n\n-- Order by selectivity\nCREATE INDEX idx_orders_composite ON orders(\n  user_id,         -- Most selective\n  status,          -- Medium selective\n  created_at       -- Least selective\n);\n```\n\n#### Full-Text Search Index (Postgres)\n\n```sql\n-- GIN index for full-text search\nCREATE INDEX idx_products_search ON products\nUSING GIN(to_tsvector('english', name || ' ' || description));\n\n-- Query\nSELECT * FROM products\nWHERE to_tsvector('english', name || ' ' || description) @@ to_tsquery('wireless & headphones');\n```\n\n#### JSONB Index (Postgres)\n\n```sql\nCREATE TABLE events (\n  id SERIAL PRIMARY KEY,\n  data JSONB\n);\n\n-- Index entire JSONB column\nCREATE INDEX idx_events_data ON events USING GIN(data);\n\n-- Index specific path\nCREATE INDEX idx_events_user_id ON events((data->>'user_id'));\n\n-- Query\nSELECT * FROM events WHERE data->>'user_id' = '123';\nSELECT * FROM events WHERE data @> '{\"type\": \"click\"}';\n```\n\n### Index Monitoring\n\n```sql\n-- Postgres: Find unused indexes\nSELECT\n  schemaname,\n  tablename,\n  indexname,\n  idx_scan AS scans,\n  pg_size_pretty(pg_relation_size(indexrelid)) AS size\nFROM pg_stat_user_indexes\nWHERE idx_scan = 0\n  AND indexrelname NOT LIKE 'pg_toast%'\nORDER BY pg_relation_size(indexrelid) DESC;\n\n-- Postgres: Find missing indexes (slow queries)\nSELECT\n  schemaname,\n  tablename,\n  seq_scan,\n  seq_tup_read,\n  idx_scan,\n  seq_tup_read \u002F seq_scan AS avg_rows_per_scan\nFROM pg_stat_user_tables\nWHERE seq_scan > 0\nORDER BY seq_tup_read DESC;\n```\n\n---\n\n## Data Types Selection\n\n### Postgres\u002FMySQL\n\n| Data Type | Use For | Example |\n|-----------|---------|---------|\n| `SERIAL` \u002F `BIGSERIAL` | Auto-increment IDs | Primary keys |\n| `VARCHAR(n)` | Variable-length text | Names, emails (use appropriate length) |\n| `TEXT` | Unlimited text | Descriptions, content |\n| `INTEGER` \u002F `BIGINT` | Whole numbers | Counts, IDs |\n| `DECIMAL(p,s)` | Exact decimals | Money, prices |\n| `FLOAT` \u002F `DOUBLE` | Approximate decimals | Scientific data (avoid for money) |\n| `BOOLEAN` | True\u002Ffalse | Flags, status |\n| `DATE` | Calendar date | Birth dates |\n| `TIMESTAMP` | Date + time | Created\u002Fupdated timestamps |\n| `TIMESTAMPTZ` | Date + time + timezone | Global app timestamps (use this!) |\n| `JSONB` (Postgres) | Structured data | Settings, metadata |\n| `UUID` | Globally unique IDs | Distributed systems |\n| `ENUM` | Fixed set of values | Status: ('pending', 'active', 'closed') |\n\n### Best Practices\n\n```sql\n-- ✅ GOOD: Use appropriate types\nCREATE TABLE users (\n  id BIGSERIAL PRIMARY KEY,                    -- Big enough for scale\n  email VARCHAR(255) NOT NULL UNIQUE,          -- Bounded length\n  password_hash VARCHAR(255) NOT NULL,         -- Fixed hash length\n  bhypocce DECIMAL(10,2) DEFAULT 0,             -- Exact decimals for money\n  is_active BOOLEAN DEFAULT true,              -- Boolean for flags\n  metadata JSONB,                              -- Flexible metadata\n  created_at TIMESTAMPTZ DEFAULT NOW()         -- Timezone-aware\n);\n\n-- ❌ BAD: Poor type choices\nCREATE TABLE users (\n  id INTEGER,                                  -- Too small (max 2B)\n  email TEXT,                                  -- Unbounded\n  bhypocce FLOAT,                               -- Inexact for money!\n  is_active INTEGER,                           -- Use BOOLEAN\n  created_at TIMESTAMP                         -- No timezone\n);\n```\n\n### MongoDB Data Types\n\n```javascript\n{\n  _id: ObjectId(\"507f1f77bcf86cd799439011\"),  \u002F\u002F Auto-generated ID\n  name: \"Alice\",                               \u002F\u002F String\n  age: 30,                                     \u002F\u002F Number (Int32\u002FInt64\u002FDouble)\n  email: \"alice@example.com\",                  \u002F\u002F String\n  tags: [\"admin\", \"premium\"],                  \u002F\u002F Array\n  address: {                                   \u002F\u002F Embedded document\n    street: \"123 Main St\",\n    city: \"New York\"\n  },\n  created_at: ISODate(\"2025-01-15T10:30:00Z\"), \u002F\u002F Date\n  metadata: {},                                \u002F\u002F Object\n  is_active: true                              \u002F\u002F Boolean\n}\n```\n\n---\n\n## Multi-Database Patterns\n\n### Postgres + Redis + ElasticSearch\n\n```\n                    Application\n                         |\n         ┌───────────────┼───────────────┐\n         |               |               |\n    Postgres          Redis       ElasticSearch\n   (Source of       (Cache)         (Search)\n     truth)\n```\n\n#### Postgres: Persistent Storage\n\n```sql\nCREATE TABLE products (\n  id SERIAL PRIMARY KEY,\n  name VARCHAR(200) NOT NULL,\n  description TEXT,\n  price DECIMAL(10,2),\n  stock INTEGER,\n  created_at TIMESTAMPTZ DEFAULT NOW()\n);\n```\n\n#### Redis: Caching Layer\n\n```javascript\n\u002F\u002F Cache product by ID (5 min TTL)\nawait redis.setex(`product:${id}`, 300, JSON.stringify(product));\n\n\u002F\u002F Get from cache\nconst cached = await redis.get(`product:${id}`);\nif (cached) return JSON.parse(cached);\n\n\u002F\u002F Cache miss - fetch from Postgres\nconst product = await db.query('SELECT * FROM products WHERE id = $1', [id]);\nawait redis.setex(`product:${id}`, 300, JSON.stringify(product));\nreturn product;\n```\n\n#### ElasticSearch: Full-Text Search\n\n```javascript\n\u002F\u002F Index product in ElasticSearch\nawait esClient.index({\n  index: 'products',\n  id: product.id,\n  body: {\n    name: product.name,\n    description: product.description,\n    price: product.price\n  }\n});\n\n\u002F\u002F Search\nconst results = await esClient.search({\n  index: 'products',\n  body: {\n    query: {\n      multi_match: {\n        query: 'wireless headphones',\n        fields: ['name^2', 'description']  \u002F\u002F Boost name field\n      }\n    }\n  }\n});\n```\n\n### Write-Through Pattern\n\n```javascript\nasync function updateProduct(id, updates) {\n  \u002F\u002F 1. Update Postgres (source of truth)\n  await db.query('UPDATE products SET name = $1 WHERE id = $2', [updates.name, id]);\n  \n  \u002F\u002F 2. Invalidate cache\n  await redis.del(`product:${id}`);\n  \n  \u002F\u002F 3. Update search index\n  await esClient.update({\n    index: 'products',\n    id: id,\n    body: { doc: updates }\n  });\n}\n```\n\n---\n\n## Schema Migration Strategies\n\n### Migration Tools\n\n**Postgres\u002FMySQL**:\n- Flyway (Java)\n- Liquibase (Java)\n- node-pg-migrate (Node.js)\n- Alembic (Python)\n- golang-migrate (Go)\n\n**MongoDB**:\n- migrate-mongo (Node.js)\n- Application-level migrations\n\n### Migration Best Practices\n\n#### Versioned Migrations\n\n```\nmigrations\u002F\n├── V001__create_users_table.sql\n├── V002__add_email_index.sql\n├── V003__add_orders_table.sql\n└── V004__add_order_status_enum.sql\n```\n\n#### Reversible Migrations\n\n```sql\n-- V005__add_user_bio.sql (UP)\nALTER TABLE users ADD COLUMN bio TEXT;\n\n-- V005__add_user_bio_rollback.sql (DOWN)\nALTER TABLE users DROP COLUMN bio;\n```\n\n#### Safe Schema Changes\n\n```sql\n-- ❌ BAD: Blocks table during migration\nALTER TABLE orders ADD COLUMN notes TEXT NOT NULL;\n\n-- ✅ GOOD: Add as nullable first, then backfill, then enforce\nALTER TABLE orders ADD COLUMN notes TEXT;  -- Non-blocking\nUPDATE orders SET notes = '' WHERE notes IS NULL;  -- Backfill\nALTER TABLE orders ALTER COLUMN notes SET NOT NULL;  -- Enforce\n\n-- ✅ GOOD: Use default to avoid backfill\nALTER TABLE orders ADD COLUMN notes TEXT NOT NULL DEFAULT '';\n```\n\n### Zero-Downtime Migrations\n\n**Pattern**: Expand → Migrate → Contract\n\n```sql\n-- Step 1: EXPAND - Add new column\nALTER TABLE users ADD COLUMN full_name VARCHAR(200);\n\n-- Application code writes to BOTH first_name and full_name\n\n-- Step 2: MIGRATE - Backfill data\nUPDATE users SET full_name = first_name || ' ' || last_name WHERE full_name IS NULL;\n\n-- Step 3: CONTRACT - Remove old columns\n-- (After all app instances updated)\nALTER TABLE users DROP COLUMN first_name;\nALTER TABLE users DROP COLUMN last_name;\n```\n\n---\n\n## Partitioning and Sharding\n\n### Table Partitioning (Postgres)\n\n#### Range Partitioning (By Date)\n\n```sql\n-- Parent table\nCREATE TABLE orders (\n  id BIGSERIAL,\n  user_id INTEGER,\n  total DECIMAL(10,2),\n  created_at TIMESTAMPTZ NOT NULL,\n  PRIMARY KEY (id, created_at)\n) PARTITION BY RANGE (created_at);\n\n-- Partitions\nCREATE TABLE orders_2025_01 PARTITION OF orders\nFOR VALUES FROM ('2025-01-01') TO ('2025-02-01');\n\nCREATE TABLE orders_2025_02 PARTITION OF orders\nFOR VALUES FROM ('2025-02-01') TO ('2025-03-01');\n\n-- Indexes on partitions\nCREATE INDEX idx_orders_2025_01_user ON orders_2025_01(user_id);\nCREATE INDEX idx_orders_2025_02_user ON orders_2025_02(user_id);\n\n-- Query (Postgres automatically prunes partitions)\nSELECT * FROM orders\nWHERE created_at >= '2025-01-15' AND created_at \u003C '2025-01-20';\n-- Only queries orders_2025_01 partition\n```\n\n#### List Partitioning (By Value)\n\n```sql\nCREATE TABLE users (\n  id BIGSERIAL,\n  email VARCHAR(255),\n  region VARCHAR(10) NOT NULL,\n  PRIMARY KEY (id, region)\n) PARTITION BY LIST (region);\n\nCREATE TABLE users_us PARTITION OF users FOR VALUES IN ('US');\nCREATE TABLE users_eu PARTITION OF users FOR VALUES IN ('EU', 'UK');\nCREATE TABLE users_asia PARTITION OF users FOR VALUES IN ('JP', 'CN', 'IN');\n```\n\n### Sharding (Application-Level)\n\n```\nApplication\n     |\n     v\nShard Router\n     |\n     ├── Shard 1 (user_id % 4 = 0)\n     ├── Shard 2 (user_id % 4 = 1)\n     ├── Shard 3 (user_id % 4 = 2)\n     └── Shard 4 (user_id % 4 = 3)\n```\n\n```javascript\n\u002F\u002F Shard routing logic\nfunction getShardForUser(userId) {\n  const shardCount = 4;\n  const shardId = userId % shardCount;\n  return shardConnections[shardId];\n}\n\n\u002F\u002F Query specific shard\nasync function getUser(userId) {\n  const db = getShardForUser(userId);\n  return await db.query('SELECT * FROM users WHERE id = $1', [userId]);\n}\n\n\u002F\u002F Cross-shard query (expensive!)\nasync function getAllActiveUsers() {\n  const results = await Promise.all(\n    shardConnections.map(db =>\n      db.query('SELECT * FROM users WHERE is_active = true')\n    )\n  );\n  return results.flat();\n}\n```\n\n---\n\n## Soft Deletes vs Hard Deletes\n\n### Hard Delete\n\n```sql\nDELETE FROM users WHERE id = 123;\n-- Data permanently removed\n```\n\n**Pros**: Simple, saves storage, enforces constraints\n**Cons**: No recovery, breaks referential integrity, no audit trail\n\n### Soft Delete\n\n```sql\n-- Add deleted_at column\nALTER TABLE users ADD COLUMN deleted_at TIMESTAMPTZ;\nCREATE INDEX idx_users_deleted ON users(deleted_at) WHERE deleted_at IS NULL;\n\n-- Soft delete\nUPDATE users SET deleted_at = NOW() WHERE id = 123;\n\n-- Query active users\nSELECT * FROM users WHERE deleted_at IS NULL;\n\n-- Restore\nUPDATE users SET deleted_at = NULL WHERE id = 123;\n```\n\n**Pros**: Recoverable, audit trail, referential integrity preserved\n**Cons**: Requires updated queries, uses storage, unique constraints tricky\n\n### Handling Unique Constraints with Soft Deletes\n\n```sql\n-- ❌ PROBLEM: Unique constraint blocks re-creation after soft delete\nCREATE UNIQUE INDEX idx_users_email ON users(email);\n-- Soft-deleted user with email \"alice@example.com\" blocks new user with same email\n\n-- ✅ SOLUTION 1: Partial unique index\nCREATE UNIQUE INDEX idx_users_email_active ON users(email)\nWHERE deleted_at IS NULL;\n-- Only active users must have unique emails\n\n-- ✅ SOLUTION 2: Composite unique index\nCREATE UNIQUE INDEX idx_users_email_deleted ON users(email, deleted_at);\n-- Allows same email if deleted_at differs\n```\n\n---\n\n## Audit Trail Patterns\n\n### Audit Table\n\n```sql\nCREATE TABLE users (\n  id SERIAL PRIMARY KEY,\n  email VARCHAR(255),\n  name VARCHAR(100),\n  updated_at TIMESTAMPTZ DEFAULT NOW()\n);\n\nCREATE TABLE users_audit (\n  audit_id SERIAL PRIMARY KEY,\n  user_id INTEGER NOT NULL,\n  email VARCHAR(255),\n  name VARCHAR(100),\n  operation VARCHAR(10) NOT NULL,  -- INSERT, UPDATE, DELETE\n  changed_by INTEGER,               -- User who made change\n  changed_at TIMESTAMPTZ DEFAULT NOW()\n);\n\n-- Trigger to log changes\nCREATE OR REPLACE FUNCTION audit_users()\nRETURNS TRIGGER AS $$\nBEGIN\n  IF (TG_OP = 'DELETE') THEN\n    INSERT INTO users_audit(user_id, email, name, operation)\n    VALUES (OLD.id, OLD.email, OLD.name, 'DELETE');\n    RETURN OLD;\n  ELSIF (TG_OP = 'UPDATE') THEN\n    INSERT INTO users_audit(user_id, email, name, operation)\n    VALUES (NEW.id, NEW.email, NEW.name, 'UPDATE');\n    RETURN NEW;\n  ELSIF (TG_OP = 'INSERT') THEN\n    INSERT INTO users_audit(user_id, email, name, operation)\n    VALUES (NEW.id, NEW.email, NEW.name, 'INSERT');\n    RETURN NEW;\n  END IF;\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE TRIGGER trg_audit_users\nAFTER INSERT OR UPDATE OR DELETE ON users\nFOR EACH ROW EXECUTE FUNCTION audit_users();\n```\n\n### Temporal Tables (Postgres)\n\n```sql\n-- System-versioned temporal table\nCREATE TABLE users (\n  id SERIAL PRIMARY KEY,\n  email VARCHAR(255),\n  name VARCHAR(100),\n  valid_from TIMESTAMPTZ DEFAULT NOW(),\n  valid_to TIMESTAMPTZ DEFAULT 'infinity'\n);\n\n-- Query current state\nSELECT * FROM users WHERE valid_to = 'infinity';\n\n-- Query historical state (as of specific time)\nSELECT * FROM users\nWHERE valid_from \u003C= '2025-01-01' AND valid_to > '2025-01-01';\n```\n\n---\n\n## Time-Series Data Patterns\n\n### TimescaleDB (Postgres Extension)\n\n```sql\nCREATE EXTENSION IF NOT EXISTS timescaledb;\n\nCREATE TABLE metrics (\n  time TIMESTAMPTZ NOT NULL,\n  device_id INTEGER NOT NULL,\n  temperature DECIMAL(5,2),\n  humidity DECIMAL(5,2)\n);\n\n-- Convert to hypertable (partitioned by time)\nSELECT create_hypertable('metrics', 'time');\n\n-- Continuous aggregate (materialized view)\nCREATE MATERIALIZED VIEW metrics_hourly\nWITH (timescaledb.continuous) AS\nSELECT\n  time_bucket('1 hour', time) AS hour,\n  device_id,\n  AVG(temperature) AS avg_temp,\n  MAX(temperature) AS max_temp,\n  MIN(temperature) AS min_temp\nFROM metrics\nGROUP BY hour, device_id;\n\n-- Automatic retention policy (delete old data)\nSELECT add_retention_policy('metrics', INTERVAL '90 days');\n```\n\n---\n\n## Graph Relationships\n\n### Adjacency List (Postgres)\n\n```sql\n-- Social graph: users follow users\nCREATE TABLE follows (\n  follower_id INTEGER REFERENCES users(id),\n  followee_id INTEGER REFERENCES users(id),\n  created_at TIMESTAMPTZ DEFAULT NOW(),\n  PRIMARY KEY (follower_id, followee_id)\n);\n\nCREATE INDEX idx_follows_follower ON follows(follower_id);\nCREATE INDEX idx_follows_followee ON follows(followee_id);\n\n-- Query: Who does Alice follow?\nSELECT u.* FROM users u\nJOIN follows f ON u.id = f.followee_id\nWHERE f.follower_id = (SELECT id FROM users WHERE email = 'alice@example.com');\n\n-- Query: Who follows Alice?\nSELECT u.* FROM users u\nJOIN follows f ON u.id = f.follower_id\nWHERE f.followee_id = (SELECT id FROM users WHERE email = 'alice@example.com');\n\n-- Query: Mutual follows (friends)\nSELECT u.* FROM users u\nWHERE EXISTS (\n  SELECT 1 FROM follows f1\n  WHERE f1.follower_id = 123 AND f1.followee_id = u.id\n)\nAND EXISTS (\n  SELECT 1 FROM follows f2\n  WHERE f2.follower_id = u.id AND f2.followee_id = 123\n);\n```\n\n---\n\n## Document Design (MongoDB)\n\n### Embedding vs Referencing\n\n#### Embedding (Denormalized)\n\n```javascript\n\u002F\u002F One-to-few relationship: Embed addresses\n{\n  _id: ObjectId(\"...\"),\n  name: \"Alice\",\n  email: \"alice@example.com\",\n  addresses: [\n    { type: \"home\", street: \"123 Main St\", city: \"NYC\" },\n    { type: \"work\", street: \"456 Office Blvd\", city: \"NYC\" }\n  ]\n}\n```\n\n**Pros**: Single query, atomic updates\n**Cons**: Document size limits (16MB), data duplication\n\n#### Referencing (Normalized)\n\n```javascript\n\u002F\u002F One-to-many relationship: Reference orders\n\u002F\u002F User document\n{\n  _id: ObjectId(\"user1\"),\n  name: \"Alice\",\n  email: \"alice@example.com\"\n}\n\n\u002F\u002F Order documents\n{\n  _id: ObjectId(\"order1\"),\n  user_id: ObjectId(\"user1\"),  \u002F\u002F Reference\n  total: 100.00,\n  items: [...]\n}\n```\n\n**Pros**: No duplication, smaller documents\n**Cons**: Multiple queries, no joins (requires $lookup)\n\n### Schema Design Rules\n\n1. **Embed** if:\n   - Data accessed together\n   - One-to-few relationship\n   - Data doesn't change frequently\n\n2. **Reference** if:\n   - Data accessed independently\n   - One-to-many or many-to-many\n   - Data changes frequently\n   - Document size would exceed 16MB\n\n---\n\n## Anti-Patterns to Avoid\n\n```\n❌ No indexes on foreign keys\n❌ Using TEXT for all strings (use VARCHAR with length)\n❌ Using FLOAT for money (use DECIMAL)\n❌ Not using transactions for multi-step operations\n❌ Selecting * instead of specific columns\n❌ Not partitioning large tables (>10M rows)\n❌ Ignoring query performance (no EXPLAIN)\n❌ Using ORMs without understanding generated SQL\n❌ Not planning for schema evolution\n❌ Premature optimization (normalize first, denormalize for performance)\n```\n\n---\n\n## Related Skills\n\n- `backend-patterns` - Service layer and repository patterns\n- `api-design` - REST API conventions\n- `fastapi-patterns` - FastAPI database integration\n- `deployment-patterns` - Database deployment strategies\n\n---\n\n**Created**: 2025-05-07\n**Category**: Backend\n**Difficulty**: Intermediate to Advanced\n**Estimated Time**: 30-60 minutes per pattern\n","# Database Design\n\n## What This Skill Does\n\nProvides production-ready database design patterns including ER modeling, normalization strategies, index optimization, multi-database architectures, and schema evolution. Covers relational (Postgres\u002FMySQL), document (MongoDB), time-series, and graph data models.\n\n## Prerequisites\n\n- Understanding of relational database concepts\n- Familiarity with at least one database system (Postgres, MySQL, MongoDB)\n- Knowledge of SQL or NoSQL query languages\n\n---\n\n## Quick Start\n\n### Choose Your Database Type\n\n```\nStructured, relational data → Postgres\u002FMySQL\nFlexible schemas, nested docs → MongoDB\nTime-series metrics → TimescaleDB\u002FInfluxDB\nGraph relationships → Neo4j\nMulti-model needs → Postgres + Redis + ElasticSearch\n```\n\n### Basic Design Workflow\n\n1. **Identify entities** → Users, Orders, Products\n2. **Define relationships** → One-to-many, many-to-many\n3. **Normalize to 3NF** → Remove redundancy\n4. **Add indexes** → For common queries\n5. **Plan migrations** → Version schema changes\n\n---\n\n## ER Diagram Design\n\n### Entity-Relationship Fundamentals\n\n**Entities**: Nouns in your domain (User, Order, Product)\n**Attributes**: Properties of entities (name, email, price)\n**Relationships**: Associations between entities (User places Order)\n\n### Relationship Types\n\n#### One-to-Many (1:N)\n\n```\nUser ──\u003C Order\n 1       N\n\nUser (1)               Order (N)\n────────              ──────────\nid (PK)               id (PK)\nemail                 user_id (FK)\nname                  total\n                      created_at\n```\n\n**Implementation**:\n```sql\nCREATE TABLE users (\n  id SERIAL PRIMARY KEY,\n  email VARCHAR(255) UNIQUE NOT NULL,\n  name VARCHAR(100) NOT NULL\n);\n\nCREATE TABLE orders (\n  id SERIAL PRIMARY KEY,\n  user_id INTEGER NOT NULL REFERENCES users(id),\n  total DECIMAL(10,2) NOT NULL,\n  created_at TIMESTAMP DEFAULT NOW()\n);\n\nCREATE INDEX idx_orders_user_id ON orders(user_id);\n```\n\n#### Many-to-Many (N:M)\n\n```\nStudent ──>\u003C Course\n   N         M\n\nStudent          Enrollment         Course\n────────        ────────────        ────────\nid (PK)         student_id (FK)     id (PK)\nname            course_id (FK)      name\n                grade               credits\n                enrolled_at\n```\n\n**Implementation**:\n```sql\nCREATE TABLE students (\n  id SERIAL PRIMARY KEY,\n  name VARCHAR(100) NOT NULL\n);\n\nCREATE TABLE courses (\n  id SERIAL PRIMARY KEY,\n  name VARCHAR(100) NOT NULL,\n  credits INTEGER NOT NULL\n);\n\n-- Junction\u002Fjoin table\nCREATE TABLE enrollments (\n  student_id INTEGER NOT NULL REFERENCES students(id),\n  course_id INTEGER NOT NULL REFERENCES courses(id),\n  grade VARCHAR(2),\n  enrolled_at TIMESTAMP DEFAULT NOW(),\n  PRIMARY KEY (student_id, course_id)\n);\n\nCREATE INDEX idx_enrollments_student ON enrollments(student_id);\nCREATE INDEX idx_enrollments_course ON enrollments(course_id);\n```\n\n#### One-to-One (1:1)\n\n```\nUser ── UserProfile\n 1        1\n\nUser                 UserProfile\n────────            ──────────────\nid (PK)             user_id (PK, FK)\nemail               bio\n                    avatar_url\n                    preferences\n```\n\n**When to Use**: Separate sensitive data, optional extensions, performance optimization.\n\n**Implementation**:\n```sql\nCREATE TABLE users (\n  id SERIAL PRIMARY KEY,\n  email VARCHAR(255) UNIQUE NOT NULL\n);\n\nCREATE TABLE user_profiles (\n  user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,\n  bio TEXT,\n  avatar_url VARCHAR(500),\n  preferences JSONB\n);\n```\n\n### Self-Referencing Relationships\n\n**Use Case**: Hierarchies, trees, graphs\n\n```\nEmployee ──\u003C Employee (manager)\n\nEmployee\n────────────────\nid (PK)\nname\nmanager_id (FK) → employees(id)\n```\n\n**Implementation**:\n```sql\nCREATE TABLE employees (\n  id SERIAL PRIMARY KEY,\n  name VARCHAR(100) NOT NULL,\n  manager_id INTEGER REFERENCES employees(id),\n  CONSTRAINT no_self_reference CHECK (id != manager_id)\n);\n\nCREATE INDEX idx_employees_manager ON employees(manager_id);\n\n-- Query: Find all direct reports\nSELECT * FROM employees WHERE manager_id = 5;\n\n-- Query: Find entire reporting chain (recursive CTE)\nWITH RECURSIVE reporting_chain AS (\n  SELECT id, name, manager_id, 1 AS level\n  FROM employees\n  WHERE id = 5\n  \n  UNION ALL\n  \n  SELECT e.id, e.name, e.manager_id, rc.level + 1\n  FROM employees e\n  JOIN reporting_chain rc ON e.manager_id = rc.id\n)\nSELECT * FROM reporting_chain ORDER BY level;\n```\n\n---\n\n## Database Normalization\n\n### First Normal Form (1NF)\n\n**Rule**: Eliminate repeating groups, ensure atomic values.\n\n```\n❌ BAD: Non-atomic values\nUser\n─────────────────────────\nid | name  | phone_numbers\n─────────────────────────\n1  | Alice | 555-1234, 555-5678\n\n✅ GOOD: Atomic values, separate table\nUser                     Phone\n────────────────        ────────────────────\nid | name               user_id | number\n────────────────        ────────────────────\n1  | Alice              1       | 555-1234\n                        1       | 555-5678\n```\n\n### Second Normal Form (2NF)\n\n**Rule**: Meet 1NF + no partial dependencies (all non-key attributes depend on entire primary key).\n\n```\n❌ BAD: Partial dependency\nOrderItem (composite key: order_id, product_id)\n─────────────────────────────────────────────\norder_id | product_id | product_name | quantity\n─────────────────────────────────────────────\n1        | 10         | Widget       | 5\n1        | 20         | Gadget       | 3\n\nproduct_name depends only on product_id (partial dependency)\n\n✅ GOOD: Remove partial dependencies\nOrderItem                        Product\n────────────────────────        ─────────────────\norder_id | product_id | qty     id | name\n────────────────────────        ─────────────────\n1        | 10         | 5       10 | Widget\n1        | 20         | 3       20 | Gadget\n```\n\n### Third Normal Form (3NF)\n\n**Rule**: Meet 2NF + no transitive dependencies.\n\n```\n❌ BAD: Transitive dependency\nEmployee\n────────────────────────────────────────────\nid | name  | dept_id | dept_name | dept_location\n────────────────────────────────────────────\n1  | Alice | 5       | Sales     | New York\n2  | Bob   | 5       | Sales     | New York\n\ndept_name and dept_location depend on dept_id (transitive)\n\n✅ GOOD: Remove transitive dependencies\nEmployee                    Department\n─────────────────          ────────────────────────\nid | name  | dept_id       id | name  | location\n─────────────────          ────────────────────────\n1  | Alice | 5             5  | Sales | New York\n2  | Bob   | 5\n```\n\n### Boyce-Codd Normal Form (BCNF)\n\n**Rule**: Meet 3NF + every determinant is a candidate key.\n\n```\n❌ BAD: Violates BCNF\nCourseProfessor\n────────────────────────────────\nstudent_id | course | professor\n────────────────────────────────\n1          | Math   | Dr. Smith\n2          | Math   | Dr. Smith\n\nAssumption: Each course has only one professor.\nprofessor → course (professor determines course)\nBut professor is not a candidate key.\n\n✅ GOOD: Split into two tables\nStudentCourse              CourseProfessor\n───────────────           ──────────────────\nstudent_id | course       course | professor\n───────────────           ──────────────────\n1          | Math         Math   | Dr. Smith\n2          | Math\n```\n\n---\n\n## When to Denormalize\n\n### Performance Tradeoffs\n\n**Normalize When**:\n- Write-heavy workloads (avoid update anomalies)\n- Storage is expensive\n- Data integrity is critical\n- Schema is stable\n\n**Denormalize When**:\n- Read-heavy workloads (reduce joins)\n- Query performance is critical\n- Aggregations are frequent\n- Data is mostly immutable\n\n### Common Denormalization Patterns\n\n#### Pattern 1: Aggregate Caching\n\n```sql\n-- Normalized\nSELECT COUNT(*) FROM orders WHERE user_id = 123;\n\n-- Denormalized: Cache count in users table\nCREATE TABLE users (\n  id SERIAL PRIMARY KEY,\n  email VARCHAR(255),\n  order_count INTEGER DEFAULT 0  -- Cached aggregate\n);\n\n-- Update via trigger\nCREATE OR REPLACE FUNCTION update_order_count()\nRETURNS TRIGGER AS $$\nBEGIN\n  UPDATE users\n  SET order_count = (SELECT COUNT(*) FROM orders WHERE user_id = NEW.user_id)\n  WHERE id = NEW.user_id;\n  RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE TRIGGER trg_update_order_count\nAFTER INSERT OR DELETE ON orders\nFOR EACH ROW EXECUTE FUNCTION update_order_count();\n```\n\n#### Pattern 2: Flattening Joins\n\n```sql\n-- Normalized: Requires join\nSELECT o.id, o.total, u.name, u.email\nFROM orders o\nJOIN users u ON o.user_id = u.id;\n\n-- Denormalized: Embed user info\nCREATE TABLE orders (\n  id SERIAL PRIMARY KEY,\n  user_id INTEGER REFERENCES users(id),\n  user_name VARCHAR(100),    -- Denormalized\n  user_email VARCHAR(255),   -- Denormalized\n  total DECIMAL(10,2)\n);\n\n-- Trade-off: Faster reads, slower writes, potential inconsistency\n```\n\n#### Pattern 3: Materialized Views\n\n```sql\n-- Create pre-computed view\nCREATE MATERIALIZED VIEW order_summaries AS\nSELECT\n  user_id,\n  COUNT(*) AS order_count,\n  SUM(total) AS lifetime_value,\n  MAX(created_at) AS last_order_date\nFROM orders\nGROUP BY user_id;\n\nCREATE INDEX idx_order_summaries_user ON order_summaries(user_id);\n\n-- Refresh periodically\nREFRESH MATERIALIZED VIEW CONCURRENTLY order_summaries;\n```\n\n---\n\n## Index Design Strategies\n\n### Index Types\n\n#### B-Tree Index (Default)\n\n**Use For**: Equality, range queries, sorting\n\n```sql\nCREATE INDEX idx_users_email ON users(email);\nCREATE INDEX idx_orders_created ON orders(created_at);\n\n-- Efficient queries\nSELECT * FROM users WHERE email = 'alice@example.com';\nSELECT * FROM orders WHERE created_at >= '2025-01-01';\nSELECT * FROM orders ORDER BY created_at DESC LIMIT 10;\n```\n\n#### Unique Index\n\n```sql\nCREATE UNIQUE INDEX idx_users_email_unique ON users(email);\n\n-- Enforces uniqueness, faster than CHECK constraint\n```\n\n#### Partial Index\n\n**Use For**: Indexing subset of rows\n\n```sql\n-- Index only active orders (reduces index size)\nCREATE INDEX idx_orders_active ON orders(user_id)\nWHERE status = 'active';\n\n-- Efficient for: WHERE user_id = X AND status = 'active'\n-- Ignored for: WHERE user_id = X AND status = 'completed'\n```\n\n#### Composite Index\n\n**Rule**: Order matters! Most selective columns first.\n\n```sql\n-- Good for: WHERE user_id = X AND status = Y\nCREATE INDEX idx_orders_user_status ON orders(user_id, status);\n\n-- Also good for: WHERE user_id = X (left prefix)\n-- NOT good for: WHERE status = Y (right side only)\n\n-- Order by selectivity\nCREATE INDEX idx_orders_composite ON orders(\n  user_id,         -- Most selective\n  status,          -- Medium selective\n  created_at       -- Least selective\n);\n```\n\n#### Full-Text Search Index (Postgres)\n\n```sql\n-- GIN index for full-text search\nCREATE INDEX idx_products_search ON products\nUSING GIN(to_tsvector('english', name || ' ' || description));\n\n-- Query\nSELECT * FROM products\nWHERE to_tsvector('english', name || ' ' || description) @@ to_tsquery('wireless & headphones');\n```\n\n#### JSONB Index (Postgres)\n\n```sql\nCREATE TABLE events (\n  id SERIAL PRIMARY KEY,\n  data JSONB\n);\n\n-- Index entire JSONB column\nCREATE INDEX idx_events_data ON events USING GIN(data);\n\n-- Index specific path\nCREATE INDEX idx_events_user_id ON events((data->>'user_id'));\n\n-- Query\nSELECT * FROM events WHERE data->>'user_id' = '123';\nSELECT * FROM events WHERE data @> '{\"type\": \"click\"}';\n```\n\n### Index Monitoring\n\n```sql\n-- Postgres: Find unused indexes\nSELECT\n  schemaname,\n  tablename,\n  indexname,\n  idx_scan AS scans,\n  pg_size_pretty(pg_relation_size(indexrelid)) AS size\nFROM pg_stat_user_indexes\nWHERE idx_scan = 0\n  AND indexrelname NOT LIKE 'pg_toast%'\nORDER BY pg_relation_size(indexrelid) DESC;\n\n-- Postgres: Find missing indexes (slow queries)\nSELECT\n  schemaname,\n  tablename,\n  seq_scan,\n  seq_tup_read,\n  idx_scan,\n  seq_tup_read \u002F seq_scan AS avg_rows_per_scan\nFROM pg_stat_user_tables\nWHERE seq_scan > 0\nORDER BY seq_tup_read DESC;\n```\n\n---\n\n## Data Types Selection\n\n### Postgres\u002FMySQL\n\n| Data Type | Use For | Example |\n|-----------|---------|---------|\n| `SERIAL` \u002F `BIGSERIAL` | Auto-increment IDs | Primary keys |\n| `VARCHAR(n)` | Variable-length text | Names, emails (use appropriate length) |\n| `TEXT` | Unlimited text | Descriptions, content |\n| `INTEGER` \u002F `BIGINT` | Whole numbers | Counts, IDs |\n| `DECIMAL(p,s)` | Exact decimals | Money, prices |\n| `FLOAT` \u002F `DOUBLE` | Approximate decimals | Scientific data (avoid for money) |\n| `BOOLEAN` | True\u002Ffalse | Flags, status |\n| `DATE` | Calendar date | Birth dates |\n| `TIMESTAMP` | Date + time | Created\u002Fupdated timestamps |\n| `TIMESTAMPTZ` | Date + time + timezone | Global app timestamps (use this!) |\n| `JSONB` (Postgres) | Structured data | Settings, metadata |\n| `UUID` | Globally unique IDs | Distributed systems |\n| `ENUM` | Fixed set of values | Status: ('pending', 'active', 'closed') |\n\n### Best Practices\n\n```sql\n-- ✅ GOOD: Use appropriate types\nCREATE TABLE users (\n  id BIGSERIAL PRIMARY KEY,                    -- Big enough for scale\n  email VARCHAR(255) NOT NULL UNIQUE,          -- Bounded length\n  password_hash VARCHAR(255) NOT NULL,         -- Fixed hash length\n  bhypocce DECIMAL(10,2) DEFAULT 0,             -- Exact decimals for money\n  is_active BOOLEAN DEFAULT true,              -- Boolean for flags\n  metadata JSONB,                              -- Flexible metadata\n  created_at TIMESTAMPTZ DEFAULT NOW()         -- Timezone-aware\n);\n\n-- ❌ BAD: Poor type choices\nCREATE TABLE users (\n  id INTEGER,                                  -- Too small (max 2B)\n  email TEXT,                                  -- Unbounded\n  bhypocce FLOAT,                               -- Inexact for money!\n  is_active INTEGER,                           -- Use BOOLEAN\n  created_at TIMESTAMP                         -- No timezone\n);\n```\n\n### MongoDB Data Types\n\n```javascript\n{\n  _id: ObjectId(\"507f1f77bcf86cd799439011\"),  \u002F\u002F Auto-generated ID\n  name: \"Alice\",                               \u002F\u002F String\n  age: 30,                                     \u002F\u002F Number (Int32\u002FInt64\u002FDouble)\n  email: \"alice@example.com\",                  \u002F\u002F String\n  tags: [\"admin\", \"premium\"],                  \u002F\u002F Array\n  address: {                                   \u002F\u002F Embedded document\n    street: \"123 Main St\",\n    city: \"New York\"\n  },\n  created_at: ISODate(\"2025-01-15T10:30:00Z\"), \u002F\u002F Date\n  metadata: {},                                \u002F\u002F Object\n  is_active: true                              \u002F\u002F Boolean\n}\n```\n\n---\n\n## Multi-Database Patterns\n\n### Postgres + Redis + ElasticSearch\n\n```\n                    Application\n                         |\n         ┌───────────────┼───────────────┐\n         |               |               |\n    Postgres          Redis       ElasticSearch\n   (Source of       (Cache)         (Search)\n     truth)\n```\n\n#### Postgres: Persistent Storage\n\n```sql\nCREATE TABLE products (\n  id SERIAL PRIMARY KEY,\n  name VARCHAR(200) NOT NULL,\n  description TEXT,\n  price DECIMAL(10,2),\n  stock INTEGER,\n  created_at TIMESTAMPTZ DEFAULT NOW()\n);\n```\n\n#### Redis: Caching Layer\n\n```javascript\n\u002F\u002F Cache product by ID (5 min TTL)\nawait redis.setex(`product:${id}`, 300, JSON.stringify(product));\n\n\u002F\u002F Get from cache\nconst cached = await redis.get(`product:${id}`);\nif (cached) return JSON.parse(cached);\n\n\u002F\u002F Cache miss - fetch from Postgres\nconst product = await db.query('SELECT * FROM products WHERE id = $1', [id]);\nawait redis.setex(`product:${id}`, 300, JSON.stringify(product));\nreturn product;\n```\n\n#### ElasticSearch: Full-Text Search\n\n```javascript\n\u002F\u002F Index product in ElasticSearch\nawait esClient.index({\n  index: 'products',\n  id: product.id,\n  body: {\n    name: product.name,\n    description: product.description,\n    price: product.price\n  }\n});\n\n\u002F\u002F Search\nconst results = await esClient.search({\n  index: 'products',\n  body: {\n    query: {\n      multi_match: {\n        query: 'wireless headphones',\n        fields: ['name^2', 'description']  \u002F\u002F Boost name field\n      }\n    }\n  }\n});\n```\n\n### Write-Through Pattern\n\n```javascript\nasync function updateProduct(id, updates) {\n  \u002F\u002F 1. Update Postgres (source of truth)\n  await db.query('UPDATE products SET name = $1 WHERE id = $2', [updates.name, id]);\n  \n  \u002F\u002F 2. Invalidate cache\n  await redis.del(`product:${id}`);\n  \n  \u002F\u002F 3. Update search index\n  await esClient.update({\n    index: 'products',\n    id: id,\n    body: { doc: updates }\n  });\n}\n```\n\n---\n\n## Schema Migration Strategies\n\n### Migration Tools\n\n**Postgres\u002FMySQL**:\n- Flyway (Java)\n- Liquibase (Java)\n- node-pg-migrate (Node.js)\n- Alembic (Python)\n- golang-migrate (Go)\n\n**MongoDB**:\n- migrate-mongo (Node.js)\n- Application-level migrations\n\n### Migration Best Practices\n\n#### Versioned Migrations\n\n```\nmigrations\u002F\n├── V001__create_users_table.sql\n├── V002__add_email_index.sql\n├── V003__add_orders_table.sql\n└── V004__add_order_status_enum.sql\n```\n\n#### Reversible Migrations\n\n```sql\n-- V005__add_user_bio.sql (UP)\nALTER TABLE users ADD COLUMN bio TEXT;\n\n-- V005__add_user_bio_rollback.sql (DOWN)\nALTER TABLE users DROP COLUMN bio;\n```\n\n#### Safe Schema Changes\n\n```sql\n-- ❌ BAD: Blocks table during migration\nALTER TABLE orders ADD COLUMN notes TEXT NOT NULL;\n\n-- ✅ GOOD: Add as nullable first, then backfill, then enforce\nALTER TABLE orders ADD COLUMN notes TEXT;  -- Non-blocking\nUPDATE orders SET notes = '' WHERE notes IS NULL;  -- Backfill\nALTER TABLE orders ALTER COLUMN notes SET NOT NULL;  -- Enforce\n\n-- ✅ GOOD: Use default to avoid backfill\nALTER TABLE orders ADD COLUMN notes TEXT NOT NULL DEFAULT '';\n```\n\n### Zero-Downtime Migrations\n\n**Pattern**: Expand → Migrate → Contract\n\n```sql\n-- Step 1: EXPAND - Add new column\nALTER TABLE users ADD COLUMN full_name VARCHAR(200);\n\n-- Application code writes to BOTH first_name and full_name\n\n-- Step 2: MIGRATE - Backfill data\nUPDATE users SET full_name = first_name || ' ' || last_name WHERE full_name IS NULL;\n\n-- Step 3: CONTRACT - Remove old columns\n-- (After all app instances updated)\nALTER TABLE users DROP COLUMN first_name;\nALTER TABLE users DROP COLUMN last_name;\n```\n\n---\n\n## Partitioning and Sharding\n\n### Table Partitioning (Postgres)\n\n#### Range Partitioning (By Date)\n\n```sql\n-- Parent table\nCREATE TABLE orders (\n  id BIGSERIAL,\n  user_id INTEGER,\n  total DECIMAL(10,2),\n  created_at TIMESTAMPTZ NOT NULL,\n  PRIMARY KEY (id, created_at)\n) PARTITION BY RANGE (created_at);\n\n-- Partitions\nCREATE TABLE orders_2025_01 PARTITION OF orders\nFOR VALUES FROM ('2025-01-01') TO ('2025-02-01');\n\nCREATE TABLE orders_2025_02 PARTITION OF orders\nFOR VALUES FROM ('2025-02-01') TO ('2025-03-01');\n\n-- Indexes on partitions\nCREATE INDEX idx_orders_2025_01_user ON orders_2025_01(user_id);\nCREATE INDEX idx_orders_2025_02_user ON orders_2025_02(user_id);\n\n-- Query (Postgres automatically prunes partitions)\nSELECT * FROM orders\nWHERE created_at >= '2025-01-15' AND created_at \u003C '2025-01-20';\n-- Only queries orders_2025_01 partition\n```\n\n#### List Partitioning (By Value)\n\n```sql\nCREATE TABLE users (\n  id BIGSERIAL,\n  email VARCHAR(255),\n  region VARCHAR(10) NOT NULL,\n  PRIMARY KEY (id, region)\n) PARTITION BY LIST (region);\n\nCREATE TABLE users_us PARTITION OF users FOR VALUES IN ('US');\nCREATE TABLE users_eu PARTITION OF users FOR VALUES IN ('EU', 'UK');\nCREATE TABLE users_asia PARTITION OF users FOR VALUES IN ('JP', 'CN', 'IN');\n```\n\n### Sharding (Application-Level)\n\n```\nApplication\n     |\n     v\nShard Router\n     |\n     ├── Shard 1 (user_id % 4 = 0)\n     ├── Shard 2 (user_id % 4 = 1)\n     ├── Shard 3 (user_id % 4 = 2)\n     └── Shard 4 (user_id % 4 = 3)\n```\n\n```javascript\n\u002F\u002F Shard routing logic\nfunction getShardForUser(userId) {\n  const shardCount = 4;\n  const shardId = userId % shardCount;\n  return shardConnections[shardId];\n}\n\n\u002F\u002F Query specific shard\nasync function getUser(userId) {\n  const db = getShardForUser(userId);\n  return await db.query('SELECT * FROM users WHERE id = $1', [userId]);\n}\n\n\u002F\u002F Cross-shard query (expensive!)\nasync function getAllActiveUsers() {\n  const results = await Promise.all(\n    shardConnections.map(db =>\n      db.query('SELECT * FROM users WHERE is_active = true')\n    )\n  );\n  return results.flat();\n}\n```\n\n---\n\n## Soft Deletes vs Hard Deletes\n\n### Hard Delete\n\n```sql\nDELETE FROM users WHERE id = 123;\n-- Data permanently removed\n```\n\n**Pros**: Simple, saves storage, enforces constraints\n**Cons**: No recovery, breaks referential integrity, no audit trail\n\n### Soft Delete\n\n```sql\n-- Add deleted_at column\nALTER TABLE users ADD COLUMN deleted_at TIMESTAMPTZ;\nCREATE INDEX idx_users_deleted ON users(deleted_at) WHERE deleted_at IS NULL;\n\n-- Soft delete\nUPDATE users SET deleted_at = NOW() WHERE id = 123;\n\n-- Query active users\nSELECT * FROM users WHERE deleted_at IS NULL;\n\n-- Restore\nUPDATE users SET deleted_at = NULL WHERE id = 123;\n```\n\n**Pros**: Recoverable, audit trail, referential integrity preserved\n**Cons**: Requires updated queries, uses storage, unique constraints tricky\n\n### Handling Unique Constraints with Soft Deletes\n\n```sql\n-- ❌ PROBLEM: Unique constraint blocks re-creation after soft delete\nCREATE UNIQUE INDEX idx_users_email ON users(email);\n-- Soft-deleted user with email \"alice@example.com\" blocks new user with same email\n\n-- ✅ SOLUTION 1: Partial unique index\nCREATE UNIQUE INDEX idx_users_email_active ON users(email)\nWHERE deleted_at IS NULL;\n-- Only active users must have unique emails\n\n-- ✅ SOLUTION 2: Composite unique index\nCREATE UNIQUE INDEX idx_users_email_deleted ON users(email, deleted_at);\n-- Allows same email if deleted_at differs\n```\n\n---\n\n## Audit Trail Patterns\n\n### Audit Table\n\n```sql\nCREATE TABLE users (\n  id SERIAL PRIMARY KEY,\n  email VARCHAR(255),\n  name VARCHAR(100),\n  updated_at TIMESTAMPTZ DEFAULT NOW()\n);\n\nCREATE TABLE users_audit (\n  audit_id SERIAL PRIMARY KEY,\n  user_id INTEGER NOT NULL,\n  email VARCHAR(255),\n  name VARCHAR(100),\n  operation VARCHAR(10) NOT NULL,  -- INSERT, UPDATE, DELETE\n  changed_by INTEGER,               -- User who made change\n  changed_at TIMESTAMPTZ DEFAULT NOW()\n);\n\n-- Trigger to log changes\nCREATE OR REPLACE FUNCTION audit_users()\nRETURNS TRIGGER AS $$\nBEGIN\n  IF (TG_OP = 'DELETE') THEN\n    INSERT INTO users_audit(user_id, email, name, operation)\n    VALUES (OLD.id, OLD.email, OLD.name, 'DELETE');\n    RETURN OLD;\n  ELSIF (TG_OP = 'UPDATE') THEN\n    INSERT INTO users_audit(user_id, email, name, operation)\n    VALUES (NEW.id, NEW.email, NEW.name, 'UPDATE');\n    RETURN NEW;\n  ELSIF (TG_OP = 'INSERT') THEN\n    INSERT INTO users_audit(user_id, email, name, operation)\n    VALUES (NEW.id, NEW.email, NEW.name, 'INSERT');\n    RETURN NEW;\n  END IF;\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE TRIGGER trg_audit_users\nAFTER INSERT OR UPDATE OR DELETE ON users\nFOR EACH ROW EXECUTE FUNCTION audit_users();\n```\n\n### Temporal Tables (Postgres)\n\n```sql\n-- System-versioned temporal table\nCREATE TABLE users (\n  id SERIAL PRIMARY KEY,\n  email VARCHAR(255),\n  name VARCHAR(100),\n  valid_from TIMESTAMPTZ DEFAULT NOW(),\n  valid_to TIMESTAMPTZ DEFAULT 'infinity'\n);\n\n-- Query current state\nSELECT * FROM users WHERE valid_to = 'infinity';\n\n-- Query historical state (as of specific time)\nSELECT * FROM users\nWHERE valid_from \u003C= '2025-01-01' AND valid_to > '2025-01-01';\n```\n\n---\n\n## Time-Series Data Patterns\n\n### TimescaleDB (Postgres Extension)\n\n```sql\nCREATE EXTENSION IF NOT EXISTS timescaledb;\n\nCREATE TABLE metrics (\n  time TIMESTAMPTZ NOT NULL,\n  device_id INTEGER NOT NULL,\n  temperature DECIMAL(5,2),\n  humidity DECIMAL(5,2)\n);\n\n-- Convert to hypertable (partitioned by time)\nSELECT create_hypertable('metrics', 'time');\n\n-- Continuous aggregate (materialized view)\nCREATE MATERIALIZED VIEW metrics_hourly\nWITH (timescaledb.continuous) AS\nSELECT\n  time_bucket('1 hour', time) AS hour,\n  device_id,\n  AVG(temperature) AS avg_temp,\n  MAX(temperature) AS max_temp,\n  MIN(temperature) AS min_temp\nFROM metrics\nGROUP BY hour, device_id;\n\n-- Automatic retention policy (delete old data)\nSELECT add_retention_policy('metrics', INTERVAL '90 days');\n```\n\n---\n\n## Graph Relationships\n\n### Adjacency List (Postgres)\n\n```sql\n-- Social graph: users follow users\nCREATE TABLE follows (\n  follower_id INTEGER REFERENCES users(id),\n  followee_id INTEGER REFERENCES users(id),\n  created_at TIMESTAMPTZ DEFAULT NOW(),\n  PRIMARY KEY (follower_id, followee_id)\n);\n\nCREATE INDEX idx_follows_follower ON follows(follower_id);\nCREATE INDEX idx_follows_followee ON follows(followee_id);\n\n-- Query: Who does Alice follow?\nSELECT u.* FROM users u\nJOIN follows f ON u.id = f.followee_id\nWHERE f.follower_id = (SELECT id FROM users WHERE email = 'alice@example.com');\n\n-- Query: Who follows Alice?\nSELECT u.* FROM users u\nJOIN follows f ON u.id = f.follower_id\nWHERE f.followee_id = (SELECT id FROM users WHERE email = 'alice@example.com');\n\n-- Query: Mutual follows (friends)\nSELECT u.* FROM users u\nWHERE EXISTS (\n  SELECT 1 FROM follows f1\n  WHERE f1.follower_id = 123 AND f1.followee_id = u.id\n)\nAND EXISTS (\n  SELECT 1 FROM follows f2\n  WHERE f2.follower_id = u.id AND f2.followee_id = 123\n);\n```\n\n---\n\n## Document Design (MongoDB)\n\n### Embedding vs Referencing\n\n#### Embedding (Denormalized)\n\n```javascript\n\u002F\u002F One-to-few relationship: Embed addresses\n{\n  _id: ObjectId(\"...\"),\n  name: \"Alice\",\n  email: \"alice@example.com\",\n  addresses: [\n    { type: \"home\", street: \"123 Main St\", city: \"NYC\" },\n    { type: \"work\", street: \"456 Office Blvd\", city: \"NYC\" }\n  ]\n}\n```\n\n**Pros**: Single query, atomic updates\n**Cons**: Document size limits (16MB), data duplication\n\n#### Referencing (Normalized)\n\n```javascript\n\u002F\u002F One-to-many relationship: Reference orders\n\u002F\u002F User document\n{\n  _id: ObjectId(\"user1\"),\n  name: \"Alice\",\n  email: \"alice@example.com\"\n}\n\n\u002F\u002F Order documents\n{\n  _id: ObjectId(\"order1\"),\n  user_id: ObjectId(\"user1\"),  \u002F\u002F Reference\n  total: 100.00,\n  items: [...]\n}\n```\n\n**Pros**: No duplication, smaller documents\n**Cons**: Multiple queries, no joins (requires $lookup)\n\n### Schema Design Rules\n\n1. **Embed** if:\n   - Data accessed together\n   - One-to-few relationship\n   - Data doesn't change frequently\n\n2. **Reference** if:\n   - Data accessed independently\n   - One-to-many or many-to-many\n   - Data changes frequently\n   - Document size would exceed 16MB\n\n---\n\n## Anti-Patterns to Avoid\n\n```\n❌ No indexes on foreign keys\n❌ Using TEXT for all strings (use VARCHAR with length)\n❌ Using FLOAT for money (use DECIMAL)\n❌ Not using transactions for multi-step operations\n❌ Selecting * instead of specific columns\n❌ Not partitioning large tables (>10M rows)\n❌ Ignoring query performance (no EXPLAIN)\n❌ Using ORMs without understanding generated SQL\n❌ Not planning for schema evolution\n❌ Premature optimization (normalize first, denormalize for performance)\n```\n\n---\n\n## Related Skills\n\n- `backend-patterns` - Service layer and repository patterns\n- `api-design` - REST API conventions\n- `fastapi-patterns` - FastAPI database integration\n- `deployment-patterns` - Database deployment strategies\n\n---\n\n**Created**: 2025-05-07\n**Category**: Backend\n**Difficulty**: Intermediate to Advanced\n**Estimated Time**: 30-60 minutes per pattern\n",{"name":5,"description":7},"main","eebcd780d62a0710aa03028091dc1e9baa995b83","hypoc\u002Fskills\u002Fdatabase-design","https:\u002F\u002Fgithub.com\u002Fpjherron\u002Fhypoc","https:\u002F\u002Fgithub.com\u002Fpjherron","2026-09-01 06:45:11",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add pjherron\u002Fhypoc --skill \"Database Design\"",{"tool":36,"command":37},"bunx","bunx skills add pjherron\u002Fhypoc --skill \"Database Design\"",{"tool":39,"command":40},"pnpm","pnpm dlx skills add pjherron\u002Fhypoc --skill \"Database Design\"","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fpjherron\u002Fhypoc\u002Fblob\u002Fmain\u002Fhypoc\u002Fskills\u002Fdatabase-design\u002FSKILL.md",true,[],[45,52,59,66,73,80],{"skillNo":46,"name":47,"nameZh":6,"description":48,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":49,"categories":50,"keywords":51,"publishedAt":19},"01M799MNB4RVHZZECC75ZFGH0Y","workspace-surface-audit","Audit the active repo, MCP servers, plugins, connectors, env surfaces, and harness setup, then recommend the highest-value ECC-native skills, hooks, agents, and operator workflows. Use when the user wants help setting up Claude Code or understanding what capabilities are actually available in their environment.","https:\u002F\u002Fgithub.com\u002Fpjherron\u002Fhypoc\u002Fblob\u002Fmain\u002Fhypoc\u002Fskills\u002Fworkspace-surface-audit\u002FSKILL.md",[],[],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M799MHR27W0YV1VMW26N691S","Verification & Quality Assurance","Comprehensive truth scoring, code quality verification, and automatic rollback system with 0.95 accuracy threshold for ensuring high-quality agent outputs and codebase reliability.","https:\u002F\u002Fgithub.com\u002Fpjherron\u002Fhypoc\u002Fblob\u002Fmain\u002Fhypoc\u002Fskills\u002Fverification-quality\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M799MEX0F1D253S3KZ1635PE","verification-loop","A comprehensive verification system for Claude Code sessions.","https:\u002F\u002Fgithub.com\u002Fpjherron\u002Fhypoc\u002Fblob\u002Fmain\u002Fhypoc\u002Fskills\u002Fverification-loop\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M799MCFN5N6A9VWM6R2TFJRK","triage","Move issues and external PRs through a state machine of triage roles — categorise, verify, grill if needed, and write agent-ready briefs.","https:\u002F\u002Fgithub.com\u002Fpjherron\u002Fhypoc\u002Fblob\u002Fmain\u002Fhypoc\u002Fskills\u002Ftriage\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M799M695F2XJBTP21YHN0R46","token-budget-advisor","Offers the user an informed choice about how much response depth to consume before answering. Use this skill when the user explicitly wants to control response length, depth, or token budget. TRIGGER when: \"token budget\", \"token count\", \"token usage\", \"token limit\", \"response length\", \"answer depth\", \"short version\", \"brief answer\", \"detailed answer\", \"exhaustive answer\", \"respuesta corta vs larga\", \"cuántos tokens\", \"ahorrar tokens\", \"responde al 50%\", \"dame la versión corta\", \"quiero controlar cuánto usas\", or clear variants where the user is explicitly asking to control answer size or depth. DO NOT TRIGGER when: user has already specified a level in the current session (maintain it), the request is clearly a one-word answer, or \"token\" refers to auth\u002Fsession\u002Fpayment tokens rather than response size.","https:\u002F\u002Fgithub.com\u002Fpjherron\u002Fhypoc\u002Fblob\u002Fmain\u002Fhypoc\u002Fskills\u002Ftoken-budget-advisor\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M799M387CZZVGC18PN0AZ70S","to-tickets","Break a plan, spec, or the current conversation into a set of tracer-bullet tickets, each declaring its blocking edges, published to the configured tracker — edges as text in a local file, or native blocking links on a real tracker.","https:\u002F\u002Fgithub.com\u002Fpjherron\u002Fhypoc\u002Fblob\u002Fmain\u002Fhypoc\u002Fskills\u002Fto-tickets\u002FSKILL.md",[],[]]