Skip to content
designing-database-schemas logo

Database Schema Designer

designing-database-schemas

Process use when you need to work with database schema design.

SKILL.md

Full skill instructions

Database Schema Designer

Overview

Design normalized relational database schemas from business requirements, entity-relationship diagrams, or existing application code. This skill produces PostgreSQL or MySQL DDL with proper data types, constraints, indexes, and relationships following normalization principles (3NF by default) with strategic denormalization where performance requires it.

Prerequisites

  • Business domain requirements or existing application models/​classes to derive schema from
  • psql or mysql CLI for testing schema DDL
  • Target database engine and version (determines available data types and features)
  • Expected data volumes and query patterns for sizing and index decisions
  • Multi-tenancy requirements (shared schema, schema-per-tenant, or database-per-tenant)

Instructions

  1. Identify all entities (nouns) from the business requirements. Each entity becomes a table. List every attribute (property) of each entity and classify as required or optional.

  2. Define primary keys for each table. Prefer BIGSERIAL (PostgreSQL) or BIGINT AUTO_INCREMENT (MySQL) for surrogate keys. Use UUID (via gen_random_uuid()) for distributed systems or when IDs are exposed in URLs. Natural keys are acceptable when truly immutable and unique (ISO country codes, IATA airport codes).

  3. Normalize the schema to Third Normal Form (3NF):

    • 1NF: Eliminate repeating groups. Each column holds a single atomic value. No arrays in columns (unless using PostgreSQL array types intentionally).
    • 2NF: Remove partial dependencies. Every non-key column depends on the entire primary key.
    • 3NF: Remove transitive dependencies. Non-key columns depend only on the primary key, not on other non-key columns. Extract lookup tables for values that change independently.
  4. Define relationships between tables:

    • One-to-many: Add a foreign key column on the "many" side referencing the "one" side. Example: orders.customer_id REFERENCES customers(id).
    • Many-to-many: Create a junction table with two foreign keys. Example: product_categories(product_id, category_id) with a composite primary key.
    • One-to-one: Add a foreign key with a UNIQUE constraint, or merge into a single table if entities are always accessed together.
  5. Choose appropriate data types with precision:

    • Money: NUMERIC(12,2) or INTEGER storing cents (never FLOAT/DOUBLE)
    • Timestamps: TIMESTAMPTZ (PostgreSQL) with time zone for events; DATE for calendar dates
    • Status fields: VARCHAR(20) with CHECK constraint, or create an ENUM type
    • Email: CITEXT (PostgreSQL) or VARCHAR(254) with CHECK constraint for format validation
    • JSON: JSONB (PostgreSQL) for flexible schema attributes; avoid for core relational data
  6. Add standard columns to every table:

    • created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
    • updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() (with trigger for auto-update)
    • deleted_at TIMESTAMPTZ for soft delete (add partial index WHERE deleted_at IS NULL)
  7. Define constraints: NOT NULL on required fields, UNIQUE on natural keys and email addresses, CHECK constraints for value validation (CHECK (price >= 0), CHECK (status IN ('active', 'inactive'))), and foreign keys with appropriate ON DELETE behavior (CASCADE, SET NULL, or RESTRICT).

  8. Design indexes based on expected query patterns:

    • Primary key index is automatic
    • Foreign key columns: always index these for JOIN performance
    • Columns in WHERE clauses with high selectivity: B-tree index
    • Full-text search columns: GIN index on tsvector
    • Composite indexes: match the most common multi-column filter patterns, leftmost column first
  9. Apply strategic denormalization where 3NF causes unacceptable query complexity:

    • Materialized views for expensive aggregate queries
    • Denormalized counter columns (with trigger-based updates) for counts displayed on every page load
    • JSON columns for flexible metadata that varies by record type
  10. Generate the complete DDL script with CREATE TABLE statements in dependency order (referenced tables first), followed by indexes, triggers, and any seed data for lookup tables.

Output

  • Complete DDL script with CREATE TABLE, constraints, indexes, and triggers in executable order
  • Entity-relationship description listing all tables, columns, types, and relationships
  • Index strategy document explaining which indexes support which query patterns
  • Seed data scripts for lookup/​reference tables (countries, statuses, categories)
  • Migration file compatible with the project's migration framework

Error Handling

ErrorCauseSolution
Circular foreign key dependencyTables reference each other, preventing creation in any orderUse ALTER TABLE ADD CONSTRAINT after both tables are created; or redesign to eliminate the cycle with a junction table
Over-normalization causing excessive JOINsEvery lookup value in its own table, queries require 8+ JOINsDenormalize low-cardinality, rarely-changing lookup values; use ENUM types for status fields instead of separate tables
NUMERIC precision overflowMonetary values exceed NUMERIC(10,2) maximumIncrease precision to NUMERIC(15,2) or NUMERIC(19,4) for currencies requiring sub-cent precision
Schema too rigid for evolving requirementsFrequent ALTER TABLE needed as business rules changeUse JSONB columns for flexible attributes; implement the EAV (Entity-Attribute-Value) pattern for truly dynamic schemas; plan for schema evolution from the start
Missing index on foreign key columnJOINs on foreign key columns cause sequential scansAlways create indexes on foreign key columns; PostgreSQL does not auto-index foreign keys (unlike MySQL InnoDB)

Examples

E-commerce schema design: Tables: customers, addresses (one-to-many from customers), products, categories (many-to-many via product_categories), orders, order_items (one-to-many from orders), payments. Money stored as NUMERIC(12,2). Soft delete on customers and products. GIN index on products.search_vector for full-text search. Composite index (customer_id, created_at DESC) on orders for order history pages.

Multi-tenant SaaS schema with row-level security: Every table includes tenant_id BIGINT NOT NULL with a foreign key to tenants. Row-level security policies enforce tenant isolation: CREATE POLICY tenant_isolation ON orders USING (tenant_id = current_setting('app.tenant_id')::bigint). Composite indexes start with tenant_id for partition-like query performance.

Event sourcing schema: An events table with (aggregate_id, sequence_number) as composite primary key, event_type VARCHAR(100), payload JSONB, created_at TIMESTAMPTZ. A snapshots table stores materialized state at periodic intervals. Append-only design with no UPDATE or DELETE operations.

Resources

More skills from jeremylongshore

openrouter-compliance-review logo
jeremylongshore/claude-code-plugins-plus-skills

openrouter-compliance-review

Review OpenRouter integration for regulatory compliance (SOC2, GDPR,

2.8K 0
View
maintainx-data-handling logo
jeremylongshore/claude-code-plugins-plus-skills

maintainx-data-handling

Data synchronization, ETL patterns, and data management for MaintainX.

2.8K 0
View
groq-core-workflow-a logo
jeremylongshore/claude-code-plugins-plus-skills

groq-core-workflow-a

Execute Groq primary workflow: chat completions with tool use and JSON

2.8K 0
View
validating-csrf-protection logo
jeremylongshore/claude-code-plugins-plus-skills

validating-csrf-protection

Validate CSRF protection implementations for security gaps. Use when

2.8K 0
View
api-contract logo
jeremylongshore/claude-code-plugins-plus-skills

api-contract

Configure this skill should be used when the user asks about "API contract",

2.8K 0
View
ideogram-incident-runbook logo
jeremylongshore/claude-code-plugins-plus-skills

ideogram-incident-runbook

Execute Ideogram incident response with triage, mitigation, and postmortem.

2.8K 0
View
gamma-sdk-patterns logo
jeremylongshore/claude-code-plugins-plus-skills

gamma-sdk-patterns

Reusable patterns for the Gamma REST API (no SDK exists).

2.8K 0
View
deepgram-sdk-patterns logo
jeremylongshore/claude-code-plugins-plus-skills

deepgram-sdk-patterns

Apply production-ready Deepgram SDK patterns for TypeScript and Python.

2.8K 0
View
openrouter-upgrade-migration logo
jeremylongshore/claude-code-plugins-plus-skills

openrouter-upgrade-migration

Migrate to OpenRouter from direct provider APIs or upgrade between SDK/model

2.8K 0
View
openrouter-common-errors logo
jeremylongshore/claude-code-plugins-plus-skills

openrouter-common-errors

Diagnose and fix common OpenRouter API errors. Use when encountering

2.8K 0
View
linear-cost-tuning logo
jeremylongshore/claude-code-plugins-plus-skills

linear-cost-tuning

Optimize Linear API usage, reduce unnecessary calls, and maximize

2.8K 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View