[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6FGF611HSNEH5MSNZEDYEEN":3,"skill-same:01M6FGF611HSNEH5MSNZEDYEEN":113},{"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":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":46,"commitSha":47,"skillDirectory":48,"forksCount":49,"repositoryHtmlUrl":50,"repositoryHomepageUrl":51,"ownerHtmlUrl":52,"ownerBlogUrl":6,"ownerDescription":53,"updatedAt":54,"install":55,"resources":68},"01M6FGF611HSNEH5MSNZEDYEEN","database-schema-design",null,"Database schema design for PostgreSQL\u002FMySQL with normalization, relationships, constraints. Use for new databases, schema reviews, migrations, or encountering missing PKs\u002FFKs, wrong data types, premature denormalization, EAV anti-pattern.","ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fsecondsky\u002Fclaude-skills\u002Fdatabase-schema-design\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"design","database","database schema design","database schema","schema","schema design","reviews","types","columns","pattern","relationship","patterns","max","databases","anti-patterns","data","audit","postgresql","mysql","delete","2026-11-10 10:12:30",false,"---\nname: database-schema-design\ndescription: Database schema design for PostgreSQL\u002FMySQL with normalization, relationships, constraints. Use for new databases, schema reviews, migrations, or encountering missing PKs\u002FFKs, wrong data types, premature denormalization, EAV anti-pattern.\nlicense: MIT\nmetadata:\n  keywords: \"database schema, schema design, database normalization, 1nf 2nf 3nf, primary key, foreign key, database relationships, one to many, many to many, data types postgresql, constraints check, audit columns, soft delete, database best practices, schema patterns, database anti-patterns, missing primary key, no foreign key, varchar max, denormalization, entity relationship, composite key, uuid vs bigserial, timestamptz\"\n---\n\n# database-schema-design\n\nComprehensive database schema design patterns for PostgreSQL and MySQL with normalization, relationships, constraints, and error prevention.\n\n---\n\n## Quick Start (10 Minutes)\n\n**Step 1**: Choose your schema pattern from templates:\n```bash\n# Basic schema with users, products, orders\ncat templates\u002Fbasic-schema.sql\n\n# Relationship patterns (1:1, 1:M, M:M)\ncat templates\u002Frelationships.sql\n\n# Constraint examples\ncat templates\u002Fconstraints.sql\n\n# Audit patterns\ncat templates\u002Faudit-columns.sql\n```\n\n**Step 2**: Apply normalization rules (at minimum 3NF):\n- **1NF**: No repeating groups, atomic values\n- **2NF**: No partial dependencies on composite keys\n- **3NF**: No transitive dependencies\n- **Load** `references\u002Fnormalization-guide.md` for detailed examples\n\n**Step 3**: Add essential elements to every table:\n```sql\nCREATE TABLE your_table (\n  -- Primary key (required)\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n\n  -- Business columns with proper types\n  name VARCHAR(200) NOT NULL,  -- Use appropriate lengths\n\n  -- Audit columns (always include)\n  created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,\n  updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL\n);\n```\n\n---\n\n## Critical Rules\n\n### ✓ Always Do\n\n| Rule | Reason |\n|------|--------|\n| **Every table has PRIMARY KEY** | Ensures row uniqueness, enables relationships |\n| **Foreign keys defined explicitly** | Enforces referential integrity, prevents orphans |\n| **Index all foreign keys** | Prevents slow JOINs, critical for performance |\n| **NOT NULL on required fields** | Data integrity, prevents NULL pollution |\n| **Audit columns (created_at, updated_at)** | Track changes, debugging, compliance |\n| **Appropriate data types** | Storage efficiency, validation, indexing |\n| **Check constraints for enums** | Enforces valid values at database level |\n| **ON DELETE\u002FUPDATE rules specified** | Prevents accidental data loss or orphans |\n\n### ✗ Never Do\n\n| Anti-Pattern | Why It's Bad |\n|--------------|--------------|\n| **VARCHAR(MAX) everywhere** | Wastes space, slows indexes, no validation |\n| **Dates as VARCHAR** | No date math, no validation, sorting broken |\n| **Missing foreign keys** | No referential integrity, orphaned records |\n| **Premature denormalization** | Hard to maintain, data anomalies |\n| **EAV (Entity-Attribute-Value)** | Query complexity, no type safety, slow |\n| **Polymorphic associations** | No foreign key integrity, complex queries |\n| **Circular dependencies** | Impossible to populate, breaks CASCADE |\n| **No indexes on foreign keys** | Extremely slow JOINs, performance killer |\n\n---\n\n## Top 7 Critical Errors\n\n### Error 1: Missing Primary Key\n**Symptom**: Cannot uniquely identify rows, duplicate data\n**Fix**:\n```sql\n-- ❌ Bad\nCREATE TABLE users (\n  email VARCHAR(255),\n  name VARCHAR(100)\n);\n\n-- ✅ Good\nCREATE TABLE users (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  email VARCHAR(255) UNIQUE NOT NULL,\n  name VARCHAR(100) NOT NULL\n);\n```\n\n### Error 2: No Foreign Key Constraints\n**Symptom**: Orphaned records, data inconsistency\n**Fix**:\n```sql\n-- ❌ Bad\nCREATE TABLE orders (\n  id UUID PRIMARY KEY,\n  user_id UUID  -- No constraint!\n);\n\n-- ✅ Good\nCREATE TABLE orders (\n  id UUID PRIMARY KEY,\n  user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE\n);\n\n-- Index the foreign key\nCREATE INDEX idx_orders_user_id ON orders(user_id);\n```\n\n### Error 3: VARCHAR(MAX) Everywhere\n**Symptom**: Wasted space, slow indexes, no validation\n**Fix**:\n```sql\n-- ❌ Bad\nCREATE TABLE products (\n  name VARCHAR(MAX),\n  sku VARCHAR(MAX),\n  status VARCHAR(MAX)\n);\n\n-- ✅ Good\nCREATE TABLE products (\n  name VARCHAR(200) NOT NULL,\n  sku VARCHAR(50) UNIQUE NOT NULL,\n  status VARCHAR(20) NOT NULL\n    CHECK (status IN ('draft', 'active', 'archived'))\n);\n```\n\n### Error 4: Wrong Data Types (Dates as Strings)\n**Symptom**: No date validation, broken sorting, no date math\n**Fix**:\n```sql\n-- ❌ Bad\nCREATE TABLE events (\n  event_date VARCHAR(50)  -- '2025-12-15' or 'Dec 15, 2025'?\n);\n\n-- ✅ Good\nCREATE TABLE events (\n  event_date DATE NOT NULL,  -- Validated, sortable\n  event_time TIMESTAMPTZ     -- With timezone\n);\n```\n\n### Error 5: No Indexes on Foreign Keys\n**Symptom**: Extremely slow JOINs, poor query performance\n**Fix**:\n```sql\n-- Always index foreign keys\nCREATE TABLE order_items (\n  order_id UUID NOT NULL REFERENCES orders(id),\n  product_id UUID NOT NULL REFERENCES products(id)\n);\n\n-- ✅ Required indexes\nCREATE INDEX idx_order_items_order_id ON order_items(order_id);\nCREATE INDEX idx_order_items_product_id ON order_items(product_id);\n```\n\n### Error 6: Missing Audit Columns\n**Symptom**: Cannot track when records created\u002Fmodified\n**Fix**:\n```sql\n-- ❌ Bad\nCREATE TABLE products (\n  id UUID PRIMARY KEY,\n  name VARCHAR(200)\n);\n\n-- ✅ Good\nCREATE TABLE products (\n  id UUID PRIMARY KEY,\n  name VARCHAR(200) NOT NULL,\n  created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,\n  updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL\n);\n\n-- Auto-update trigger (PostgreSQL)\nCREATE TRIGGER products_updated_at\nBEFORE UPDATE ON products\nFOR EACH ROW\nEXECUTE FUNCTION update_updated_at_column();\n```\n\n### Error 7: EAV Anti-Pattern\n**Symptom**: Complex queries, no type safety, slow performance\n**Fix**:\n```sql\n-- ❌ Bad (EAV)\nCREATE TABLE product_attributes (\n  product_id UUID,\n  attribute_name VARCHAR(100),  -- 'color', 'size', 'price'\n  attribute_value TEXT           -- Everything as text!\n);\n\n-- ✅ Good (Structured + JSONB)\nCREATE TABLE products (\n  id UUID PRIMARY KEY,\n  name VARCHAR(200) NOT NULL,\n  price DECIMAL(10,2) NOT NULL,  -- Required fields as columns\n  color VARCHAR(50),              -- Common attributes as columns\n  size VARCHAR(20),\n  attributes JSONB                -- Optional\u002Fdynamic attributes\n);\n\n-- Index JSONB\nCREATE INDEX idx_products_attributes ON products USING GIN(attributes);\n```\n\n**Load** `references\u002Ferror-catalog.md` for all 12 errors with detailed fixes.\n\n---\n\n## Common Schema Patterns\n\n| Pattern | Use Case | Template |\n|---------|----------|----------|\n| **Basic CRUD** | Standard users\u002Fproducts\u002Forders | `templates\u002Fbasic-schema.sql` |\n| **One-to-One** | User → Profile | `templates\u002Frelationships.sql` (lines 7-17) |\n| **One-to-Many** | User → Orders | `templates\u002Frelationships.sql` (lines 23-34) |\n| **Many-to-Many** | Students ↔ Courses | `templates\u002Frelationships.sql` (lines 40-60) |\n| **Hierarchical** | Categories tree, org chart | `templates\u002Frelationships.sql` (lines 66-83) |\n| **Soft Delete** | Mark deleted, keep history | `templates\u002Faudit-columns.sql` (lines 55-80) |\n| **Versioning** | Track changes over time | `templates\u002Faudit-columns.sql` (lines 86-108) |\n| **Multi-Tenant** | Isolated data per organization | `references\u002Fschema-design-patterns.md` (lines 228-258) |\n\n---\n\n## Normalization Quick Reference\n\n| Form | Rule | Example |\n|------|------|---------|\n| **1NF** | Atomic values, no repeating groups | `phone1, phone2` → `phones` table |\n| **2NF** | 1NF + no partial dependencies | Composite key dependency → separate table |\n| **3NF** | 2NF + no transitive dependencies | `user.city` → `city.id` reference |\n| **BCNF** | 3NF + every determinant is candidate key | Rare edge cases |\n| **4NF** | BCNF + no multi-valued dependencies | Complex many-to-many |\n| **5NF** | 4NF + no join dependencies | Very rare, academic |\n\n**Recommendation**: Design to 3NF, denormalize only with measured performance data.\n\n**Load** `references\u002Fnormalization-guide.md` for detailed examples with before\u002Fafter.\n\n---\n\n## Configuration Summary\n\n### PostgreSQL Recommended Types\n\n```sql\n-- Primary Keys\nid UUID PRIMARY KEY DEFAULT gen_random_uuid()\n-- OR for performance-critical:\nid BIGSERIAL PRIMARY KEY\n\n-- Text\nname VARCHAR(200) NOT NULL\ndescription TEXT\ncode CHAR(10)  -- Fixed-length codes only\n\n-- Numbers\nprice DECIMAL(10,2) NOT NULL  -- Money: NEVER use FLOAT\nquantity INT NOT NULL\nrating DECIMAL(3,2)  -- 0.00 to 9.99\n\n-- Dates\u002FTimes\ncreated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL  -- With timezone\nevent_date DATE\nduration INTERVAL\n\n-- Boolean\nis_active BOOLEAN DEFAULT true NOT NULL\n\n-- JSON\nattributes JSONB  -- Binary, faster, indexable\n\n-- Enum Alternative (preferred over ENUM type)\nstatus VARCHAR(20) NOT NULL\n  CHECK (status IN ('draft', 'active', 'archived'))\n```\n\n### MySQL Differences\n\n```sql\n-- MySQL doesn't have:\nTIMESTAMPTZ  -- Use TIMESTAMP (stored as UTC)\ngen_random_uuid()  -- Use UUID() function\nJSONB  -- Use JSON (same performance in 8.0+)\n\n-- MySQL equivalent:\nid CHAR(36) PRIMARY KEY DEFAULT (UUID())\n-- OR:\nid BIGINT AUTO_INCREMENT PRIMARY KEY\n\ncreated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL\nattributes JSON\n```\n\n**Load** `references\u002Fdata-types-guide.md` for comprehensive type selection guide.\n\n---\n\n## When to Load References\n\n### Schema Design Process\n**Load** `references\u002Fschema-design-patterns.md` when:\n- Starting a new database design\n- Need pattern examples (audit columns, soft deletes, versioning)\n- Implementing multi-tenancy\n- Choosing between UUID vs BIGSERIAL\n- Following naming conventions\n\n### Normalization\n**Load** `references\u002Fnormalization-guide.md` when:\n- Schema has data duplication\n- Unsure what normal form you're in\n- Need to normalize existing schema\n- Planning database structure\n\n### Relationships\n**Load** `references\u002Frelationship-patterns.md` when:\n- Defining table relationships\n- Implementing junction tables\n- Creating hierarchical structures\n- Setting up cascade rules\n\n### Data Types\n**Load** `references\u002Fdata-types-guide.md` when:\n- Choosing column types\n- Migrating between PostgreSQL\u002FMySQL\n- Optimizing storage\n- Implementing JSON fields\n\n### Constraints\n**Load** `references\u002Fconstraints-catalog.md` when:\n- Adding validation rules\n- Implementing CHECK constraints\n- Setting up foreign key cascades\n- Creating unique constraints\n\n### Error Prevention\n**Load** `references\u002Ferror-catalog.md` when:\n- Schema review needed\n- Troubleshooting schema issues\n- All 12 documented errors with fixes\n\n---\n\n## Complete Setup Checklist\n\n**Before Creating Tables**:\n- [ ] Normalized to at least 3NF\n- [ ] All relationships identified\n- [ ] Data types chosen appropriately\n- [ ] Cascade rules defined\n\n**Every Table Must Have**:\n- [ ] Primary key defined\n- [ ] Audit columns (created_at, updated_at)\n- [ ] NOT NULL on required fields\n- [ ] Appropriate VARCHAR lengths (not MAX)\n- [ ] CHECK constraints for enums\u002Franges\n\n**Foreign Keys**:\n- [ ] All foreign keys defined with REFERENCES\n- [ ] ON DELETE\u002FUPDATE actions specified\n- [ ] All foreign keys indexed\n\n**Indexes**:\n- [ ] Foreign keys indexed\n- [ ] Frequently queried columns indexed\n- [ ] Composite indexes for multi-column queries\n\n**Validation**:\n- [ ] No circular dependencies\n- [ ] No EAV patterns\n- [ ] No polymorphic associations\n- [ ] Proper data types (no dates as strings)\n\n---\n\n## Production Example\n\n**Before** (Multiple issues):\n```sql\nCREATE TABLE users (\n  email VARCHAR(MAX),           -- Issue: No primary key, VARCHAR(MAX)\n  password VARCHAR(MAX),\n  created VARCHAR(50)           -- Issue: Date as string\n);\n\nCREATE TABLE orders (\n  id UUID PRIMARY KEY,\n  user_email VARCHAR(MAX),      -- Issue: No foreign key\n  total VARCHAR(20),            -- Issue: Money as string\n  status VARCHAR(MAX)           -- Issue: No validation\n);\n```\n\n**After** (Production-ready):\n```sql\nCREATE TABLE users (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  email VARCHAR(255) UNIQUE NOT NULL,\n  password_hash VARCHAR(255) NOT NULL,\n  created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,\n  updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL\n);\n\nCREATE TABLE orders (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n  total DECIMAL(10,2) NOT NULL CHECK (total >= 0),\n  status VARCHAR(20) NOT NULL DEFAULT 'pending'\n    CHECK (status IN ('pending', 'processing', 'shipped', 'delivered', 'canceled')),\n  created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,\n  updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL\n);\n\nCREATE INDEX idx_orders_user_id ON orders(user_id);\nCREATE INDEX idx_orders_status ON orders(status);\n```\n\n**Result**: ✅ All constraints enforced, proper types, indexed, auditable\n\n---\n\n## Known Issues Prevention\n\nAll 12 documented errors prevented:\n1. ✅ Missing primary key → UUID\u002FBIGSERIAL required\n2. ✅ No foreign key constraints → REFERENCES required\n3. ✅ VARCHAR(MAX) everywhere → Appropriate lengths\n4. ✅ Denormalization without justification → 3NF minimum\n5. ✅ Missing NOT NULL constraints → Required fields marked\n6. ✅ No indexes on foreign keys → All FKs indexed\n7. ✅ Wrong data types → Proper type selection\n8. ✅ Missing CHECK constraints → Validation rules\n9. ✅ No audit columns → created_at\u002Fupdated_at required\n10. ✅ Circular dependencies → Dependency analysis\n11. ✅ Missing ON DELETE\u002FUPDATE cascades → Cascade rules\n12. ✅ EAV anti-pattern → Structured schema + JSONB\n\n**See**: `references\u002Ferror-catalog.md` for detailed fixes\n\n---\n\n## Resources\n\n**Templates**:\n- `templates\u002Fbasic-schema.sql` - Users, products, orders starter\n- `templates\u002Frelationships.sql` - All relationship types\n- `templates\u002Fconstraints.sql` - Constraint examples\n- `templates\u002Faudit-columns.sql` - Audit patterns + triggers\n\n**References**:\n- `references\u002Fnormalization-guide.md` - 1NF through 5NF detailed\n- `references\u002Frelationship-patterns.md` - Relationship types\n- `references\u002Fdata-types-guide.md` - PostgreSQL vs MySQL types\n- `references\u002Fconstraints-catalog.md` - All constraints\n- `references\u002Fschema-design-patterns.md` - Best practices\n- `references\u002Ferror-catalog.md` - All 12 errors documented\n\n**Official Documentation**:\n- PostgreSQL Data Types: https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fdatatype.html\n- PostgreSQL Constraints: https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fddl-constraints.html\n- MySQL Data Types: https:\u002F\u002Fdev.mysql.com\u002Fdoc\u002Frefman\u002F8.0\u002Fen\u002Fdata-types.html\n\n---\n\n**Production-tested** | **12 errors prevented** | **MIT License**\n","# database-schema-design\n\nComprehensive database schema design patterns for PostgreSQL and MySQL with normalization, relationships, constraints, and error prevention.\n\n---\n\n## Quick Start (10 Minutes)\n\n**Step 1**: Choose your schema pattern from templates:\n```bash\n# Basic schema with users, products, orders\ncat templates\u002Fbasic-schema.sql\n\n# Relationship patterns (1:1, 1:M, M:M)\ncat templates\u002Frelationships.sql\n\n# Constraint examples\ncat templates\u002Fconstraints.sql\n\n# Audit patterns\ncat templates\u002Faudit-columns.sql\n```\n\n**Step 2**: Apply normalization rules (at minimum 3NF):\n- **1NF**: No repeating groups, atomic values\n- **2NF**: No partial dependencies on composite keys\n- **3NF**: No transitive dependencies\n- **Load** `references\u002Fnormalization-guide.md` for detailed examples\n\n**Step 3**: Add essential elements to every table:\n```sql\nCREATE TABLE your_table (\n  -- Primary key (required)\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n\n  -- Business columns with proper types\n  name VARCHAR(200) NOT NULL,  -- Use appropriate lengths\n\n  -- Audit columns (always include)\n  created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,\n  updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL\n);\n```\n\n---\n\n## Critical Rules\n\n### ✓ Always Do\n\n| Rule | Reason |\n|------|--------|\n| **Every table has PRIMARY KEY** | Ensures row uniqueness, enables relationships |\n| **Foreign keys defined explicitly** | Enforces referential integrity, prevents orphans |\n| **Index all foreign keys** | Prevents slow JOINs, critical for performance |\n| **NOT NULL on required fields** | Data integrity, prevents NULL pollution |\n| **Audit columns (created_at, updated_at)** | Track changes, debugging, compliance |\n| **Appropriate data types** | Storage efficiency, validation, indexing |\n| **Check constraints for enums** | Enforces valid values at database level |\n| **ON DELETE\u002FUPDATE rules specified** | Prevents accidental data loss or orphans |\n\n### ✗ Never Do\n\n| Anti-Pattern | Why It's Bad |\n|--------------|--------------|\n| **VARCHAR(MAX) everywhere** | Wastes space, slows indexes, no validation |\n| **Dates as VARCHAR** | No date math, no validation, sorting broken |\n| **Missing foreign keys** | No referential integrity, orphaned records |\n| **Premature denormalization** | Hard to maintain, data anomalies |\n| **EAV (Entity-Attribute-Value)** | Query complexity, no type safety, slow |\n| **Polymorphic associations** | No foreign key integrity, complex queries |\n| **Circular dependencies** | Impossible to populate, breaks CASCADE |\n| **No indexes on foreign keys** | Extremely slow JOINs, performance killer |\n\n---\n\n## Top 7 Critical Errors\n\n### Error 1: Missing Primary Key\n**Symptom**: Cannot uniquely identify rows, duplicate data\n**Fix**:\n```sql\n-- ❌ Bad\nCREATE TABLE users (\n  email VARCHAR(255),\n  name VARCHAR(100)\n);\n\n-- ✅ Good\nCREATE TABLE users (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  email VARCHAR(255) UNIQUE NOT NULL,\n  name VARCHAR(100) NOT NULL\n);\n```\n\n### Error 2: No Foreign Key Constraints\n**Symptom**: Orphaned records, data inconsistency\n**Fix**:\n```sql\n-- ❌ Bad\nCREATE TABLE orders (\n  id UUID PRIMARY KEY,\n  user_id UUID  -- No constraint!\n);\n\n-- ✅ Good\nCREATE TABLE orders (\n  id UUID PRIMARY KEY,\n  user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE\n);\n\n-- Index the foreign key\nCREATE INDEX idx_orders_user_id ON orders(user_id);\n```\n\n### Error 3: VARCHAR(MAX) Everywhere\n**Symptom**: Wasted space, slow indexes, no validation\n**Fix**:\n```sql\n-- ❌ Bad\nCREATE TABLE products (\n  name VARCHAR(MAX),\n  sku VARCHAR(MAX),\n  status VARCHAR(MAX)\n);\n\n-- ✅ Good\nCREATE TABLE products (\n  name VARCHAR(200) NOT NULL,\n  sku VARCHAR(50) UNIQUE NOT NULL,\n  status VARCHAR(20) NOT NULL\n    CHECK (status IN ('draft', 'active', 'archived'))\n);\n```\n\n### Error 4: Wrong Data Types (Dates as Strings)\n**Symptom**: No date validation, broken sorting, no date math\n**Fix**:\n```sql\n-- ❌ Bad\nCREATE TABLE events (\n  event_date VARCHAR(50)  -- '2025-12-15' or 'Dec 15, 2025'?\n);\n\n-- ✅ Good\nCREATE TABLE events (\n  event_date DATE NOT NULL,  -- Validated, sortable\n  event_time TIMESTAMPTZ     -- With timezone\n);\n```\n\n### Error 5: No Indexes on Foreign Keys\n**Symptom**: Extremely slow JOINs, poor query performance\n**Fix**:\n```sql\n-- Always index foreign keys\nCREATE TABLE order_items (\n  order_id UUID NOT NULL REFERENCES orders(id),\n  product_id UUID NOT NULL REFERENCES products(id)\n);\n\n-- ✅ Required indexes\nCREATE INDEX idx_order_items_order_id ON order_items(order_id);\nCREATE INDEX idx_order_items_product_id ON order_items(product_id);\n```\n\n### Error 6: Missing Audit Columns\n**Symptom**: Cannot track when records created\u002Fmodified\n**Fix**:\n```sql\n-- ❌ Bad\nCREATE TABLE products (\n  id UUID PRIMARY KEY,\n  name VARCHAR(200)\n);\n\n-- ✅ Good\nCREATE TABLE products (\n  id UUID PRIMARY KEY,\n  name VARCHAR(200) NOT NULL,\n  created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,\n  updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL\n);\n\n-- Auto-update trigger (PostgreSQL)\nCREATE TRIGGER products_updated_at\nBEFORE UPDATE ON products\nFOR EACH ROW\nEXECUTE FUNCTION update_updated_at_column();\n```\n\n### Error 7: EAV Anti-Pattern\n**Symptom**: Complex queries, no type safety, slow performance\n**Fix**:\n```sql\n-- ❌ Bad (EAV)\nCREATE TABLE product_attributes (\n  product_id UUID,\n  attribute_name VARCHAR(100),  -- 'color', 'size', 'price'\n  attribute_value TEXT           -- Everything as text!\n);\n\n-- ✅ Good (Structured + JSONB)\nCREATE TABLE products (\n  id UUID PRIMARY KEY,\n  name VARCHAR(200) NOT NULL,\n  price DECIMAL(10,2) NOT NULL,  -- Required fields as columns\n  color VARCHAR(50),              -- Common attributes as columns\n  size VARCHAR(20),\n  attributes JSONB                -- Optional\u002Fdynamic attributes\n);\n\n-- Index JSONB\nCREATE INDEX idx_products_attributes ON products USING GIN(attributes);\n```\n\n**Load** `references\u002Ferror-catalog.md` for all 12 errors with detailed fixes.\n\n---\n\n## Common Schema Patterns\n\n| Pattern | Use Case | Template |\n|---------|----------|----------|\n| **Basic CRUD** | Standard users\u002Fproducts\u002Forders | `templates\u002Fbasic-schema.sql` |\n| **One-to-One** | User → Profile | `templates\u002Frelationships.sql` (lines 7-17) |\n| **One-to-Many** | User → Orders | `templates\u002Frelationships.sql` (lines 23-34) |\n| **Many-to-Many** | Students ↔ Courses | `templates\u002Frelationships.sql` (lines 40-60) |\n| **Hierarchical** | Categories tree, org chart | `templates\u002Frelationships.sql` (lines 66-83) |\n| **Soft Delete** | Mark deleted, keep history | `templates\u002Faudit-columns.sql` (lines 55-80) |\n| **Versioning** | Track changes over time | `templates\u002Faudit-columns.sql` (lines 86-108) |\n| **Multi-Tenant** | Isolated data per organization | `references\u002Fschema-design-patterns.md` (lines 228-258) |\n\n---\n\n## Normalization Quick Reference\n\n| Form | Rule | Example |\n|------|------|---------|\n| **1NF** | Atomic values, no repeating groups | `phone1, phone2` → `phones` table |\n| **2NF** | 1NF + no partial dependencies | Composite key dependency → separate table |\n| **3NF** | 2NF + no transitive dependencies | `user.city` → `city.id` reference |\n| **BCNF** | 3NF + every determinant is candidate key | Rare edge cases |\n| **4NF** | BCNF + no multi-valued dependencies | Complex many-to-many |\n| **5NF** | 4NF + no join dependencies | Very rare, academic |\n\n**Recommendation**: Design to 3NF, denormalize only with measured performance data.\n\n**Load** `references\u002Fnormalization-guide.md` for detailed examples with before\u002Fafter.\n\n---\n\n## Configuration Summary\n\n### PostgreSQL Recommended Types\n\n```sql\n-- Primary Keys\nid UUID PRIMARY KEY DEFAULT gen_random_uuid()\n-- OR for performance-critical:\nid BIGSERIAL PRIMARY KEY\n\n-- Text\nname VARCHAR(200) NOT NULL\ndescription TEXT\ncode CHAR(10)  -- Fixed-length codes only\n\n-- Numbers\nprice DECIMAL(10,2) NOT NULL  -- Money: NEVER use FLOAT\nquantity INT NOT NULL\nrating DECIMAL(3,2)  -- 0.00 to 9.99\n\n-- Dates\u002FTimes\ncreated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL  -- With timezone\nevent_date DATE\nduration INTERVAL\n\n-- Boolean\nis_active BOOLEAN DEFAULT true NOT NULL\n\n-- JSON\nattributes JSONB  -- Binary, faster, indexable\n\n-- Enum Alternative (preferred over ENUM type)\nstatus VARCHAR(20) NOT NULL\n  CHECK (status IN ('draft', 'active', 'archived'))\n```\n\n### MySQL Differences\n\n```sql\n-- MySQL doesn't have:\nTIMESTAMPTZ  -- Use TIMESTAMP (stored as UTC)\ngen_random_uuid()  -- Use UUID() function\nJSONB  -- Use JSON (same performance in 8.0+)\n\n-- MySQL equivalent:\nid CHAR(36) PRIMARY KEY DEFAULT (UUID())\n-- OR:\nid BIGINT AUTO_INCREMENT PRIMARY KEY\n\ncreated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL\nattributes JSON\n```\n\n**Load** `references\u002Fdata-types-guide.md` for comprehensive type selection guide.\n\n---\n\n## When to Load References\n\n### Schema Design Process\n**Load** `references\u002Fschema-design-patterns.md` when:\n- Starting a new database design\n- Need pattern examples (audit columns, soft deletes, versioning)\n- Implementing multi-tenancy\n- Choosing between UUID vs BIGSERIAL\n- Following naming conventions\n\n### Normalization\n**Load** `references\u002Fnormalization-guide.md` when:\n- Schema has data duplication\n- Unsure what normal form you're in\n- Need to normalize existing schema\n- Planning database structure\n\n### Relationships\n**Load** `references\u002Frelationship-patterns.md` when:\n- Defining table relationships\n- Implementing junction tables\n- Creating hierarchical structures\n- Setting up cascade rules\n\n### Data Types\n**Load** `references\u002Fdata-types-guide.md` when:\n- Choosing column types\n- Migrating between PostgreSQL\u002FMySQL\n- Optimizing storage\n- Implementing JSON fields\n\n### Constraints\n**Load** `references\u002Fconstraints-catalog.md` when:\n- Adding validation rules\n- Implementing CHECK constraints\n- Setting up foreign key cascades\n- Creating unique constraints\n\n### Error Prevention\n**Load** `references\u002Ferror-catalog.md` when:\n- Schema review needed\n- Troubleshooting schema issues\n- All 12 documented errors with fixes\n\n---\n\n## Complete Setup Checklist\n\n**Before Creating Tables**:\n- [ ] Normalized to at least 3NF\n- [ ] All relationships identified\n- [ ] Data types chosen appropriately\n- [ ] Cascade rules defined\n\n**Every Table Must Have**:\n- [ ] Primary key defined\n- [ ] Audit columns (created_at, updated_at)\n- [ ] NOT NULL on required fields\n- [ ] Appropriate VARCHAR lengths (not MAX)\n- [ ] CHECK constraints for enums\u002Franges\n\n**Foreign Keys**:\n- [ ] All foreign keys defined with REFERENCES\n- [ ] ON DELETE\u002FUPDATE actions specified\n- [ ] All foreign keys indexed\n\n**Indexes**:\n- [ ] Foreign keys indexed\n- [ ] Frequently queried columns indexed\n- [ ] Composite indexes for multi-column queries\n\n**Validation**:\n- [ ] No circular dependencies\n- [ ] No EAV patterns\n- [ ] No polymorphic associations\n- [ ] Proper data types (no dates as strings)\n\n---\n\n## Production Example\n\n**Before** (Multiple issues):\n```sql\nCREATE TABLE users (\n  email VARCHAR(MAX),           -- Issue: No primary key, VARCHAR(MAX)\n  password VARCHAR(MAX),\n  created VARCHAR(50)           -- Issue: Date as string\n);\n\nCREATE TABLE orders (\n  id UUID PRIMARY KEY,\n  user_email VARCHAR(MAX),      -- Issue: No foreign key\n  total VARCHAR(20),            -- Issue: Money as string\n  status VARCHAR(MAX)           -- Issue: No validation\n);\n```\n\n**After** (Production-ready):\n```sql\nCREATE TABLE users (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  email VARCHAR(255) UNIQUE NOT NULL,\n  password_hash VARCHAR(255) NOT NULL,\n  created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,\n  updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL\n);\n\nCREATE TABLE orders (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n  total DECIMAL(10,2) NOT NULL CHECK (total >= 0),\n  status VARCHAR(20) NOT NULL DEFAULT 'pending'\n    CHECK (status IN ('pending', 'processing', 'shipped', 'delivered', 'canceled')),\n  created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,\n  updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL\n);\n\nCREATE INDEX idx_orders_user_id ON orders(user_id);\nCREATE INDEX idx_orders_status ON orders(status);\n```\n\n**Result**: ✅ All constraints enforced, proper types, indexed, auditable\n\n---\n\n## Known Issues Prevention\n\nAll 12 documented errors prevented:\n1. ✅ Missing primary key → UUID\u002FBIGSERIAL required\n2. ✅ No foreign key constraints → REFERENCES required\n3. ✅ VARCHAR(MAX) everywhere → Appropriate lengths\n4. ✅ Denormalization without justification → 3NF minimum\n5. ✅ Missing NOT NULL constraints → Required fields marked\n6. ✅ No indexes on foreign keys → All FKs indexed\n7. ✅ Wrong data types → Proper type selection\n8. ✅ Missing CHECK constraints → Validation rules\n9. ✅ No audit columns → created_at\u002Fupdated_at required\n10. ✅ Circular dependencies → Dependency analysis\n11. ✅ Missing ON DELETE\u002FUPDATE cascades → Cascade rules\n12. ✅ EAV anti-pattern → Structured schema + JSONB\n\n**See**: `references\u002Ferror-catalog.md` for detailed fixes\n\n---\n\n## Resources\n\n**Templates**:\n- `templates\u002Fbasic-schema.sql` - Users, products, orders starter\n- `templates\u002Frelationships.sql` - All relationship types\n- `templates\u002Fconstraints.sql` - Constraint examples\n- `templates\u002Faudit-columns.sql` - Audit patterns + triggers\n\n**References**:\n- `references\u002Fnormalization-guide.md` - 1NF through 5NF detailed\n- `references\u002Frelationship-patterns.md` - Relationship types\n- `references\u002Fdata-types-guide.md` - PostgreSQL vs MySQL types\n- `references\u002Fconstraints-catalog.md` - All constraints\n- `references\u002Fschema-design-patterns.md` - Best practices\n- `references\u002Ferror-catalog.md` - All 12 errors documented\n\n**Official Documentation**:\n- PostgreSQL Data Types: https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fdatatype.html\n- PostgreSQL Constraints: https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fddl-constraints.html\n- MySQL Data Types: https:\u002F\u002Fdev.mysql.com\u002Fdoc\u002Frefman\u002F8.0\u002Fen\u002Fdata-types.html\n\n---\n\n**Production-tested** | **12 errors prevented** | **MIT License**\n",{"name":5,"license":15,"metadata":44,"description":7},{"keywords":45},"database schema, schema design, database normalization, 1nf 2nf 3nf, primary key, foreign key, database relationships, one to many, many to many, data types postgresql, constraints check, audit columns, soft delete, database best practices, schema patterns, database anti-patterns, missing primary key, no foreign key, varchar max, denormalization, entity relationship, composite key, uuid vs bigserial, timestamptz","main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002Fsecondsky\u002Fclaude-skills\u002Fdatabase-schema-design",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":8,"skillName":5,"commands":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill database-schema-design",{"tool":61,"command":62},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill database-schema-design",{"tool":64,"command":65},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill database-schema-design","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fsecondsky\u002Fclaude-skills\u002Fdatabase-schema-design\u002FSKILL.md",true,[69,75,79,83,87,91,95,101,105,109],{"path":70,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":73,"sourceHtmlUrl":74},"references\u002Fconstraints-catalog.md","REFERENCE","参考文档",5790,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fsecondsky\u002Fclaude-skills\u002Fdatabase-schema-design\u002Freferences\u002Fconstraints-catalog.md",{"path":76,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":77,"sourceHtmlUrl":78},"references\u002Fdata-types-guide.md",4554,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fsecondsky\u002Fclaude-skills\u002Fdatabase-schema-design\u002Freferences\u002Fdata-types-guide.md",{"path":80,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":81,"sourceHtmlUrl":82},"references\u002Ferror-catalog.md",14883,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fsecondsky\u002Fclaude-skills\u002Fdatabase-schema-design\u002Freferences\u002Ferror-catalog.md",{"path":84,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":85,"sourceHtmlUrl":86},"references\u002Fnormalization-guide.md",4057,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fsecondsky\u002Fclaude-skills\u002Fdatabase-schema-design\u002Freferences\u002Fnormalization-guide.md",{"path":88,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":89,"sourceHtmlUrl":90},"references\u002Frelationship-patterns.md",3098,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fsecondsky\u002Fclaude-skills\u002Fdatabase-schema-design\u002Freferences\u002Frelationship-patterns.md",{"path":92,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":93,"sourceHtmlUrl":94},"references\u002Fschema-design-patterns.md",7782,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fsecondsky\u002Fclaude-skills\u002Fdatabase-schema-design\u002Freferences\u002Fschema-design-patterns.md",{"path":96,"resourceType":97,"resourceTypeDesc":98,"sizeBytes":99,"sourceHtmlUrl":100},"templates\u002Faudit-columns.sql","OTHER","其他",3710,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fsecondsky\u002Fclaude-skills\u002Fdatabase-schema-design\u002Ftemplates\u002Faudit-columns.sql",{"path":102,"resourceType":97,"resourceTypeDesc":98,"sizeBytes":103,"sourceHtmlUrl":104},"templates\u002Fbasic-schema.sql",1490,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fsecondsky\u002Fclaude-skills\u002Fdatabase-schema-design\u002Ftemplates\u002Fbasic-schema.sql",{"path":106,"resourceType":97,"resourceTypeDesc":98,"sizeBytes":107,"sourceHtmlUrl":108},"templates\u002Fconstraints.sql",3227,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fsecondsky\u002Fclaude-skills\u002Fdatabase-schema-design\u002Ftemplates\u002Fconstraints.sql",{"path":110,"resourceType":97,"resourceTypeDesc":98,"sizeBytes":111,"sourceHtmlUrl":112},"templates\u002Frelationships.sql",2267,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fsecondsky\u002Fclaude-skills\u002Fdatabase-schema-design\u002Ftemplates\u002Frelationships.sql",[114,123,132,141,147,153],{"skillNo":115,"name":116,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":39},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[],[120,121,122],"model","model hierarchy","model hierarchy skill",{"skillNo":124,"name":125,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":126,"categories":127,"keywords":128,"publishedAt":39},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[],[129,130,131],"MCP","zoom","zoom mcp",{"skillNo":133,"name":134,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":135,"categories":136,"keywords":137,"publishedAt":39},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[138,139,140,130],"sdk","zoom apps sdk","apps",{"skillNo":142,"name":143,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":144,"categories":145,"keywords":146,"publishedAt":39},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[143],{"skillNo":148,"name":149,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":150,"categories":151,"keywords":152,"publishedAt":39},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[],[149],{"skillNo":154,"name":155,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":156,"categories":157,"keywords":158,"publishedAt":39},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[155]]