Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
pixel-process-ug avatar

Database Schema Design

  • 67 installs
  • 1 repo stars
  • Updated March 16, 2026
  • pixel-process-ug/superkit-agents

Helps with design & ui/ux tasks.

About

database-schema-design is a Claude Code skill for design & ui/ux. It helps solo builders move faster with AI-assisted development.

  • database-schema-design
  • Design & UI/UX
  • AI-coding skill

Database Schema Design by the numbers

  • 67 all-time installs (skills.sh)
  • +2 installs in the week ending Aug 4, 2026 (Skillselion tracking)
  • Ranked #1,191 of 1,880 Design & UI/UX skills by installs in the Skillselion catalog
  • Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/pixel-process-ug/superkit-agents --skill database-schema-design

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs67
repo stars1
Last updatedMarch 16, 2026
Repositorypixel-process-ug/superkit-agents

What it does

Helps with design & ui/ux tasks.

Files

SKILL.mdMarkdownGitHub ↗

Database Schema Design

Overview

Guide the design, implementation, and optimization of database schemas with sound data modeling, safe migrations, effective indexing, and appropriate query patterns. This skill covers the full lifecycle from conceptual modeling through physical optimization, ensuring schemas that are normalized, performant, and safely evolvable.

Announce at start: "I'm using the database-schema-design skill to design the database schema."

Phase 1: Discovery and Conceptual Model

Ask these questions to understand the data requirements:

#QuestionWhat It Determines
1What entities does the system manage?Table names
2What are the relationships between entities?Foreign keys, join tables
3What are the key attributes of each entity?Column definitions
4What are the primary query patterns?Index strategy
5What is the expected data volume? (rows, growth rate)Partitioning, scaling
6What is the read/write ratio?Normalization vs denormalization
7SQL or NoSQL? (or both?)Storage engine selection

Storage Engine Decision Table

FactorChoose SQL (PostgreSQL, MySQL)Choose Document (MongoDB)Choose Key-Value (Redis)
Data shapeStructured, relationalSemi-structured, nestedSimple lookups, caching
Query complexityComplex joins, aggregationsDocument-level queriesKey-based access only
Consistency needsACID requiredEventual consistency OKEphemeral or cached data
Schema evolutionMigrations manageableSchema-free flexibilityNo schema
Scale patternVertical first, then read replicasHorizontal shardingIn-memory, limited size

STOP after discovery — present the conceptual model (entities, relationships, cardinality) for confirmation.

Phase 2: Logical Model Design

Translate the conceptual model into tables, columns, types, and constraints.

Column Design Rules

DecisionGuidance
Primary keysUUIDs for distributed systems, auto-increment for single-node
Column typesUse the most specific type (timestamptz not varchar for dates)
NullabilityDefault NOT NULL; allow NULL only when absence is meaningful
DefaultsSet sensible defaults (created_at DEFAULT now())
ConstraintsAdd CHECK, UNIQUE, and FK constraints at the schema level
Namingsnake_case, singular table names or plural — be consistent

Normalization Guide

Normal FormRuleViolation ExampleFix
1NFAtomic values, no repeating groupstags VARCHAR "urgent,priority,vip"Separate order_tags table
2NFAll non-key columns depend on entire PKproduct_name in order_items (composite PK)Move to products table
3NFNo transitive dependenciescity depends on zip_code, not user_idSeparate zip_codes table

Rule: Always start normalized. Denormalize only with measured evidence.

Denormalization Decision Table

ScenarioPatternWhen to Apply
Read-heavy dashboardsMaterialized views or summary tablesMeasured slow query
Frequently joined dataEmbed as JSONB columnJoin is >80% of query time
Reporting / analyticsSeparate denormalized reporting tablesOLAP workload
Caching layerComputed columns refreshed on writeHigh-frequency reads

Relationship Patterns

RelationshipImplementationIndex Needed
One-to-OneFK with UNIQUE constraint on childOn FK column
One-to-ManyFK on the "many" sideOn FK column
Many-to-ManyJunction/join table with composite PKOn both FK columns
PolymorphicSeparate FK columns with CHECK constraint (preferred) or type+id patternOn type+id or each FK
Self-referential (trees)parent_id FK to same table; or ltree/materialized pathOn parent_id or path

STOP after logical model — present the table definitions for review.

Phase 3: Physical Model and Indexing

Index Type Decision Table

Index TypeBest ForExample
B-tree (default)Equality and range queriesCREATE INDEX idx_users_email ON users(email)
GINFull-text search, JSONB, arraysCREATE INDEX idx_posts_search ON posts USING GIN(to_tsvector('english', body))
PartialSubset of rows matching conditionCREATE INDEX idx_active_users ON users(email) WHERE active = true
Covering (INCLUDE)Index-only scans avoiding table lookupCREATE INDEX idx_users_email ON users(email) INCLUDE (name)
CompositeMulti-column queriesCREATE INDEX idx_orders ON orders(tenant_id, status)

Composite Index Column Order

PositionColumn TypeReason
FirstHigh-cardinality equality columnsMost selective filter first
MiddleAdditional equality columnsFurther narrows results
LastRange columns (dates, numbers)Range scan on remaining rows

Rule: A composite index on (A, B, C) supports queries on A, A+B, A+B+C — but NOT B alone or C alone.

Query Optimization Checklist

Signal in EXPLAIN ANALYZEProblemFix
Seq Scan on large tableMissing indexAdd appropriate index
Nested Loop with large outer tableInefficient joinAdd index or restructure query
High actual vs estimated rowsStale statisticsRun ANALYZE on table
Hash Join high memorywork_mem too lowTune work_mem or restructure

N+1 Detection and Prevention

-- N+1 problem (bad):
SELECT * FROM users;
-- Then for EACH user: SELECT * FROM orders WHERE user_id = ?;

-- Fixed with join:
SELECT u.*, o.* FROM users u LEFT JOIN orders o ON o.user_id = u.id;

-- Fixed with batch load:
SELECT * FROM orders WHERE user_id = ANY($1);

STOP after physical model — present indexes and optimization strategy for review.

Phase 4: Migration Strategy

Zero-Downtime Migration (Expand-Contract)

Never make a breaking change in a single migration. Use two phases:

Expand phase (backward compatible): 1. Add new column/table (nullable or with default) 2. Deploy code that writes to both old and new 3. Backfill existing data in batches 4. Deploy code that reads from new

Contract phase (after all code uses new schema): 1. Remove code that writes to old 2. Drop old column/table

Migration Safety Rules

RuleRationale
Every migration has a corresponding rollbackSafe to revert
Test rollback in staging before productionVerify reversibility
Data-destructive rollbacks need explicit approvalPrevent accidental data loss
Keep migration files immutable once appliedReproducible state
Backfill large tables in batches (1000 rows)Avoid table locks

Backfill Pattern

-- Backfill in chunks of 1000
UPDATE users SET display_name = username
WHERE display_name IS NULL
AND id IN (SELECT id FROM users WHERE display_name IS NULL LIMIT 1000);

Migration Type Decision Table

Change TypeSafe ApproachDangerous Approach
Add columnAdd nullable or with defaultAdd NOT NULL without default
Remove columnExpand-contract (two deploys)Drop column directly
Rename columnAdd new, copy data, drop oldALTER RENAME (breaks queries)
Add indexCREATE INDEX CONCURRENTLYCREATE INDEX (locks table)
Change column typeAdd new column, migrate dataALTER COLUMN TYPE (locks table)

STOP after migration plan — confirm rollback strategy before finalizing.

Phase 5: Save and Transition

After explicit approval:

1. Save schema design to docs/database/ or generate migration files 2. Commit with message: docs(db): add schema design for <feature>

Transition Decision Table

User IntentNext SkillRationale
"Create the migrations"planningPlan migration implementation
"Write specs for this"spec-writingBehavioral specs for data operations
"Implement the schema"test-driven-developmentTDD with migration tests
"Just save the design"NoneSchema design is the deliverable
"Review for performance"performance-optimizationAnalyze query patterns

ORM Guidance

ORMLanguageStrengthWatch Out For
PrismaTypeScriptType-safe schema, migrationsN+1 in nested queries, limited raw SQL
DrizzleTypeScriptSQL-like API, lightweightNewer ecosystem, fewer guides
SQLAlchemyPythonMature, flexible, raw SQL supportComplex session management
GORMGoConvention-based, auto-migrateSilent failures, implicit behavior

ORM Best Practices

  • Always review generated SQL (enable query logging in development)
  • Use eager loading to prevent N+1 queries
  • Write raw SQL for complex queries rather than fighting the ORM
  • Use ORM migrations, not auto-sync in production
  • Test query performance with realistic data volumes

Connection Pooling

  • Use a connection pooler (PgBouncer, built-in pool)
  • Pool size formula: connections = (CPU cores * 2) + disk spindles
  • Use transaction-level pooling for most workloads
  • Application servers should not open raw connections

Anti-Patterns / Common Mistakes

MistakeWhy It Is WrongWhat To Do Instead
No foreign key constraintsOrphaned data, broken relationshipsAlways define FK constraints
VARCHAR for everythingLoses type safety, wastes storageUse specific types (timestamptz, int, uuid)
No indexes on FK columnsSlow joins on related tablesIndex every FK column
Premature denormalizationComplexity without measured benefitStart normalized, denormalize with evidence
Dropping columns directlyBreaks running application codeUse expand-contract pattern
CREATE INDEX without CONCURRENTLYLocks table during index creationAlways use CONCURRENTLY in production
Auto-sync schema in productionUnpredictable destructive changesUse explicit migration files
No rollback plan for migrationsCannot recover from failed deployWrite down migration for every up migration
Nullable columns everywhereLoses data integrity guaranteesDefault NOT NULL, allow NULL intentionally

Anti-Rationalization Guards

  • Do NOT skip the conceptual model — understand entities and relationships first
  • Do NOT add indexes speculatively — measure query patterns first
  • Do NOT denormalize without measured evidence of a performance problem
  • Do NOT create migrations without rollback plans
  • Do NOT skip the discovery phase — understand query patterns and data volume
  • Do NOT drop columns or tables without expand-contract pattern in production

Documentation Lookup (Context7)

Use mcp__context7__resolve-library-id then mcp__context7__query-docs for up-to-date docs. Returned docs override memorized knowledge.

  • prisma — for schema syntax, relations, or migration API
  • typeorm — for entity decorators, repository patterns, or query builder
  • knex — for query builder syntax, migrations, or seed files

---

Integration Points

SkillRelationship
api-designUpstream: API resources map to database entities
spec-writingUpstream: specs define data persistence requirements
planningDownstream: schema design informs implementation plan
test-driven-developmentDownstream: migration tests written before migration code
performance-optimizationDownstream: query optimization after schema is live
reverse-engineering-specsUpstream: reverse-engineer existing schema behavior
senior-backendParallel: backend specialist for ORM and query patterns

Verification Gate

Before claiming the schema design is complete:

1. VERIFY all entities and relationships are modeled 2. VERIFY normalization is at least 3NF (or denormalization is justified) 3. VERIFY indexes are defined for all query patterns and FK columns 4. VERIFY migration strategy includes rollback for every step 5. VERIFY the user has approved the schema design 6. VERIFY connection pooling strategy is defined for production

Skill Type

Flexible — Adapt storage engine, normalization level, and index strategy to project needs while preserving the conceptual-to-physical modeling progression, migration safety rules, and measured-evidence-before-denormalization principle.

Related skills

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.