MySQL schema examples

MySQL and InnoDB-shaped schemas: auto-increment keys, CURRENT_TIMESTAMP defaults, and composite indexes ordered for the queries that matter. Open any of them in the free drawDB editor and export ready-to-run MySQL DDL — tables, keys, indexes and comments.

85 schemas here, from 10 to 15 tables (1056 tables and 9357 columns in total), written for PostgreSQL, SQL Server, MySQL. Each one ships an ER diagram you can open and edit, a column-by-column reference, design notes explaining the trade-offs, and SQL for all six dialects. Recurring themes across the set: scheduling, inventory, marketplace, catalog, gaming.

PostgreSQL
SaaS

A/B testing & experimentation platform schema

An experimentation platform end to end: experiments and weighted variants, deterministic hash bucketing, exposure events, metric definitions, per-variant aggregates with sufficient statistics, significance results and staged rollout.

PostgreSQL
Travel

Airbnb database schema

How a short-term rental marketplace models its data: hosts and listings, a host-owned per-night calendar, request-to-book versus instant book, reservations, guest payments and host payouts, and two-way reviews that only reveal once both sides have written.

PostgreSQL
Commerce

Amazon-style marketplace database schema

How a marketplace models many sellers listing the same product: a shared catalogue, competing offers, the buy box decision as a log, orders split into per-seller sub-orders, fulfilment, payouts and product-level reviews.

PostgreSQL
Developer tools

API gateway & rate limiting database schema

How an API platform is modelled: consumers and applications, hashed API keys with scopes and rotation, upstream services and routes, rate limit policies, durable usage counters, rolled-up aggregates, sampled request logs, plans, quotas and overage billing.

PostgreSQL
Internal tools

Applicant tracking & recruiting database schema

An ATS modelled end to end: jobs with openings and hiring teams, candidates separate from applications, per-job pipeline stages, interviews with panels, structured scorecards, offers with approval chains and a talent pool of near misses.

SQL Server
Internal tools

IT asset management database schema

How an IT estate is tracked end to end: models versus serialised assets, custody history, software licences and seat allocation with compliance counts, warranties and support contracts, maintenance, depreciation, audits and disposal.

PostgreSQL
Media & content

Blog & CMS database schema

A content management schema that survives contact with editors: posts with an append-only revision history, categories and tags, threaded comments, a real media library, slug redirects and a double opt-in newsletter list.

PostgreSQL
Productivity

Calendar and scheduling database schema

How a calendar app models its data: calendars and sharing, events with their own time zones, RRULE recurrence with exception dates and per-occurrence overrides, attendees and RSVP, reminders, working hours and a free-busy index.

MySQL
Travel

Car rental and fleet database schema

A vehicle rental schema: branches, vehicle classes versus the individual cars behind them, a per-branch availability calendar, reservations and signed agreements, mileage and fuel, damage inspections with photos, protection add-ons and one-way fees.

PostgreSQL
Developer tools

CI/CD build pipeline database schema

How a build system models its data: versioned pipeline definitions, immutable runs triggered by a commit, stages with approval gates, a job DAG stored as edges, runners and capabilities, attempts and retries, artifacts, caches and streamed logs.

MySQL
Healthcare

Clinic appointment scheduling database schema

Outpatient scheduling in MySQL: recurring availability templates that generate slots, appointments that consume exactly one slot, waitlists that backfill cancellations, two-way reminders, referrals, and a dated no-show policy.

PostgreSQL
Education

Coursera-style online course platform database schema

How a MOOC platform models its data: versioned course content, dated session runs, an outline tree of modules and lectures, quizzes drawn from question banks, peer-graded assignments with rubric criteria, entitlements and certificates.

PostgreSQL
Internal tools

Sales CRM & pipeline database schema

A sales CRM modelled end to end: accounts and contacts, leads converted into an account, contact and deal, deals moving through stages with full stage history, activities, quotes, forecasts, territories and custom fields.

PostgreSQL
Communication

Discord chat platform database schema

How a community chat platform models its data: servers with nested channels, roles carrying permission bitfields, three-state per-channel overwrites, per-server nicknames, messages and threads, reactions, attachments, invites and voice sessions.

PostgreSQL
Food & drink

DoorDash food delivery database schema

How a food delivery marketplace models its data: restaurant menus built from reusable modifier groups, orders that snapshot every chosen option, courier dispatch offers, live location tracking, and the fee split between restaurant, courier and platform.

PostgreSQL
Productivity

Dropbox-style file storage & sync database schema

How a cloud drive models its data: a folder tree, versioned files, content-addressed blocks that deduplicate identical uploads to a single copy, shares and expiring public links, per-device sync cursors, trash retention and quota accounting.

PostgreSQL
Education

Duolingo-style language learning database schema

How a gamified language app models its data: directional courses, a skill tree with unlock rules, lessons and exercise items, crown levels, a per-word spaced-repetition schedule, streaks with freezes, hearts and weekly leagues.

PostgreSQL
Commerce

E-commerce store database schema

A production-shaped e-commerce schema: products with variants, inventory per location, carts, orders with snapshotted line items, payments and shipments. Open it in the editor or export SQL for six dialects.

PostgreSQL
SaaS

Email marketing & campaign database schema

How a campaign sender stores its data: lists and contacts with custom fields, rule-based segments, campaigns with A/B variants, one send row per recipient, opens and clicks, bounces and suppressions, and drip automations.

PostgreSQL
Communication

Email & mailbox service database schema

How a webmail service models its data: labels applied many-to-many instead of IMAP folders, one stored copy per message, conversation threading, attachments deduplicated by content hash, delivery filters, drafts, read state, spam scoring and quota.

PostgreSQL
Developer tools

Error tracking and monitoring database schema

How an error monitoring service models its data: projects and releases, raw events with stack frames and breadcrumbs, grouping into issues by fingerprint, resolve and regression detection, alert rules and event sampling.

MySQL
Gaming

Esports tournament and bracket database schema

How a tournament platform models competition: single and double elimination, round robin and Swiss stages, teams with roster locks, a bracket stored as a node tree, best-of series with per-map results, venues and prize distribution.

MySQL
Commerce

Etsy-style handmade marketplace database schema

How a handmade marketplace models its data: shops and sections, made-to-order listings with variations and personalisation, cross-shop carts, orders split per shop, shipping profiles and photo reviews.

PostgreSQL
Travel

Event ticketing and seat reservation schema

A ticketing schema built around expiring checkout holds: venues with sections and seats, events, general-admission capacity pools, per-seat inventory, orders, tickets with rotating QR identifiers, transfers, door scans and partial refunds.

PostgreSQL
Social

Facebook database schema

How a social network models its data: symmetric friendships stored as one canonical row, posts with audience scoping, typed reactions, groups with membership roles, pages, and events with RSVPs.

PostgreSQL
Developer tools

Feature flag service database schema

How a feature management platform stores its data: flags and variations, per-environment settings, ordered targeting rules, reusable segments, percentage rollouts with deterministic bucketing, scheduled changes and a full audit trail.

PostgreSQL
Logistics

Vehicle fleet management database schema

How a vehicle fleet is modelled: vehicles and drivers, licence entitlements with expiry, assignment history, downsampled telematics and fault codes, maintenance due by mileage or date, work orders and parts, fuel, inspections and incidents.

PostgreSQL
Travel

Flight booking and airline reservation schema

An airline reservation schema: airports, scheduled flights and their legs, weekly operating patterns, dated departures, fare classes with overlapping inventory buckets, PNR bookings, e-tickets, seat maps and assignments, and ancillaries.

MySQL
Communication

Discussion forum and community database schema

The phpBB and Discourse shape rather than the Reddit one: curated categories and boards, threads bumped by replies, flat numbered posts with quoting, reputation and badges, a report-driven moderation queue and private messages.

PostgreSQL
Developer tools

GitHub code hosting database schema

How a code hosting platform models its data: users and organisations, repositories, refs and commits, issues and pull requests sharing one number sequence, reviews with comments anchored to a file and line, labels, milestones and workflow runs.

MySQL
Media & content

Goodreads book cataloguing database schema

How a book cataloguing site models its data: works split from editions and ISBNs, contributors with roles, default and custom shelves, reading progress, ratings and reviews, series ordering and a friend activity feed.

PostgreSQL
Food & drink

Online grocery delivery database schema

How an online supermarket models its data: per-store catalogue and pricing, weight-priced items billed on what was actually picked, baskets, substitution preferences and real substitutions, picking tasks, capacity-limited delivery windows and inventory counts.

PostgreSQL
SaaS

Help desk & customer support ticketing schema

A support desk modelled properly: tickets in queues, one thread that mixes public replies with internal notes, SLA clocks measured in business hours with breach tracking, macros, tags, merges and CSAT.

MySQL
Travel

Hotel booking & reservation database schema

A reservation system that actually handles availability: room types versus rooms, rate plans, a per-night rate and inventory calendar, reservations broken down by night, payments and verified reviews.

SQL Server
Internal tools

HR and payroll database schema

How an HR system models data that must never be overwritten: employees, positions and reporting lines as dated rows, compensation history, payroll runs and itemised payslips, tax withholding, time off as a ledger, and benefits enrolment.

PostgreSQL
Gaming

In-game economy and virtual currency database schema

How a game backend models virtual currency: hard and soft currencies, player wallets, an append-only double-entry ledger of every source and sink, a personalised item shop, validated store receipts, refunds and a battle pass.

PostgreSQL
Social

Instagram database schema

How a photo-sharing app models its data: asymmetric follows with pending requests for private accounts, posts carrying an ordered carousel of media, likes and two-level comments, stories that expire, saved collections and direct messages.

MySQL
Fintech

Freelance invoicing and billing database schema

How a freelance and small-business invoicing app models its data in MySQL: clients and projects, tracked time, invoices with per-line tax, partial payments, credit notes, recurring templates, reminder schedules and multi-currency with the rate snapshotted at issue.

MySQL
Internal tools

IT helpdesk and service desk database schema

An internal service desk modelled properly: a service catalogue, incidents and requests, ordered approval chains, change requests with risk and rollback plans, linked assets, versioned knowledge base articles, SLA clocks that pause, and satisfaction ratings.

PostgreSQL
Logistics

Last-mile delivery & route planning database schema

Delivery operations modelled properly: depots, drivers and shifts, vehicle capacity constraints, orders with time windows, routes planned per day, stops in planned and actual sequence, geofenced arrivals, failed attempts, proof of delivery and re-sequencing history.

PostgreSQL
Gaming

Game leaderboards and achievements database schema

How a game backend models progression: score submissions, leaderboards scoped global or regional or friends across daily and seasonal periods, rank derived rather than stored, multi-step achievements with progress, unlock rewards and anti-cheat flags.

MySQL
Education

Public library catalog and circulation database schema

How a public library models its data: works, editions and barcoded copies, branches and holdings, members, loans with renewals, a positioned hold queue, fines and payments, and inter-branch transfers.

PostgreSQL
Social

LinkedIn database schema

How a professional network models its data: profiles with a date-ranged career history, symmetric connections created from invitations, canonical skills with endorsements, company pages, job postings and applications, and a feed.

PostgreSQL
Gaming

Multiplayer matchmaking database schema

How a competitive game backend matches players: skill ratings with uncertainty and full rating history, parties, regional queues, accept-or-decline proposals, server allocation, match rosters with backfill and abandonment penalties.

PostgreSQL
Gaming

MMO game inventory and item database schema

How an online game models items: templates versus instances, stacking rules, affixes rolled per copy, bags and bank and equipped slots, soulbinding, durability, two-sided player trades, mail with attachments and an append-only item audit log.

PostgreSQL
Media & content

Netflix video streaming database schema

How a video streaming service models its data: films and series in one titles table, seasons and episodes, profiles inside an account, resume positions, per-region licensing windows, My List, ratings and subtitle tracks.

PostgreSQL
Media & content

News site paywall database schema

How a digital newspaper models a metered paywall: articles with revisions, the per-reader meter, plans and subscriptions, gift links, newsletters and moderated comments.

PostgreSQL
Productivity

Notion workspace database schema

How a docs-and-databases workspace models its data: nested pages, a document stored as an ordered block tree, user-defined databases whose rows are pages, views with filters and sorts, inherited permissions and block-anchored comments.

PostgreSQL
Developer tools

Package registry database schema

How a package manager backend stores its data: packages and immutable published versions, integrity hashes, dependency ranges, movable dist tags like latest and beta, owners and scoped access tokens, download rollups, deprecations and yanks.

PostgreSQL
Logistics

Parcel tracking and courier network schema

A courier network schema built on an append-only scan log: shipments and the packages inside them, hubs and planned routes, scan events as the only truth, derived status, delivery attempts, exceptions, proof of delivery, and promised versus actual delivery.

PostgreSQL
Healthcare

Pharmacy dispensing & inventory database schema

How a dispensing pharmacy models its data: a drug catalogue by strength and form, stock held as batches with expiry dates picked first-expired-first-out, dispense events, interaction and allergy checks, insurance claims and a controlled-drugs register.

PostgreSQL
Social

Pinterest database schema

How a visual bookmarking app models its data: images deduplicated by content hash, pins as saves rather than uploads, repins as a self-reference to the source pin, boards with sections and collaborators, follows of both people and boards, and saved searches.

PostgreSQL
Internal tools

Project management & issue tracker database schema

A Jira-shaped tracker: projects with human-readable issue keys, subtasks through a self-reference, fractional board positions for drag-and-drop, labels, milestones, comments, attachments and a worklog.

PostgreSQL
Real estate

Property portal and real estate listings database schema

How a property portal models its data: properties as durable things versus listings as repeatable campaigns, agents and agencies, ordered media, amenities, price history as rows, viewings, offers and saved searches with alerts.

PostgreSQL
Real estate

Rental property management database schema

Landlord operations modelled end to end: buildings and units, leases and renewals, co-tenants and guarantors, rent charges generated per period, payments allocated against them, deposits held and returned, maintenance with vendors, and inspections.

MySQL
Education

Quiz and assessment engine database schema

A quiz engine that handles four question types at once: reusable question banks, draw rules and randomised papers, typed answer keys, per-question responses, partial credit, negative marking and time limits.

PostgreSQL
Social

Reddit database schema

How a forum models its data: subreddits and subscriptions, link and text posts, arbitrarily deep comment trees stored as materialised paths, narrow vote tables, karma, flairs, and an append-only moderation log with removal reasons.

MySQL
Food & drink

Restaurant point of sale database schema

How a dining-room POS models its data: floor plan tables and seats, open checks, courses and fire times, kitchen tickets routed per station, sold-out items, split checks, cashier shifts and tip-outs.

MySQL
Commerce

Retail point of sale database schema

How an in-store point of sale is modelled: stores and registers, cashier shifts with opening float and closing count, sales with discounted lines, multi-tender payment, returns against the original sale, drawer movements and approved price overrides.

PostgreSQL
Logistics

Returns & RMA (reverse logistics) database schema

How returns are actually modelled: RMA authorisations and eligibility windows, versioned policies, return reasons, inbound inspection and grading, dispositions from restock to scrap, refunds against exchanges and store credit, labels, restocking fees and return-abuse signals.

PostgreSQL
Fintech

Robinhood-style stock trading database schema

How a retail brokerage models its data: accounts and instruments, orders with type and time-in-force, partial fills, positions derived from executions with average cost basis, cash settlement, dividends, watchlists and price alerts.

PostgreSQL
SaaS

Multi-tenant SaaS database schema

Shared-database multi-tenancy done properly: organizations as tenants, global users joined through memberships, invitations, scoped API keys, plans, subscriptions, metered usage and an append-only audit log.

MySQL
Education

School & learning management system database schema

Courses versus sections, terms, enrolments that carry the final grade, prerequisites as a self-join, assignments with weights, per-attempt submissions and idempotent attendance registers.

PostgreSQL
Commerce

Shopify-style multi-store platform database schema

How a hosted commerce platform models many shops at once: merchants and shops as tenants, per-shop staff roles, catalogue and orders scoped by shop_id, installed apps with OAuth scopes, and webhook delivery attempts.

PostgreSQL
Communication

Slack team chat database schema

How a team chat product models its data: workspaces and per-workspace identity, public private and shared channels, a read cursor per member instead of a read flag per message, thread replies, mentions, files, saved items and installed apps with granted scopes.

PostgreSQL
Social

Social network database schema

Followers, feeds and direct messages modelled for read volume: asymmetric follows, one posts table for replies and reposts, narrow like rows, per-participant read pointers and notifications.

PostgreSQL
Media & content

Spotify music streaming database schema

How a music streaming service models its data: artists, albums and tracks, credited roles on a track, ordered playlists with collaborators, saved library, offline downloads and an append-only play log.

PostgreSQL
Developer tools

Status page & incident communication database schema

How a public status page is modelled: a component hierarchy with status history, incidents and severities, the timestamped public timeline, scheduled maintenance windows, email and webhook subscribers with delivery tracking, uptime samples, computed uptime and postmortems.

PostgreSQL
Healthcare

Strava-style fitness tracking database schema

How a fitness tracking app models its data: activities with compressed sensor streams instead of one row per second, segments and segment efforts with materialised leaderboards, personal records, kudos and comments, clubs, gear mileage and training load.

PostgreSQL
Fintech

Stripe-style payments platform database schema

How a payment processor models its data: merchant accounts, tokenised payment methods, the payment intent state machine, charges and partial refunds, chargebacks with evidence deadlines, payouts, webhook deliveries and idempotency keys.

PostgreSQL
Commerce

Subscription box database schema

How recurring physical commerce is modelled: plans and subscriptions, one row per billing cycle, preferences that drive curation, per-cycle box contents, shipments, skips and pauses, churn reasons and referral credit.

PostgreSQL
Healthcare

Telemedicine platform database schema

How a virtual care product models its data: clinician licences per state with expiry dates driving who may treat whom, bookable slots, video consultations with a waiting room, intake forms, e-prescriptions routed to a pharmacy, and per-region pricing.

PostgreSQL
Social

TikTok database schema

How a short-video app models its data: sounds as first-class rows reused across videos, duets and stitches as self-references, an append-only watch-event log feeding a recommendation feed, plus follows, likes, comments and hashtags.

PostgreSQL
Social

Tinder dating app database schema

How a dating app models its data: profiles with ordered photos, discovery preferences, an append-only swipe log, matches created only on a mutual right swipe, messaging scoped to a match, blocks and reports, and consumable boosts and super likes.

PostgreSQL
Productivity

Trello kanban board database schema

How a kanban board app models its data: boards, lists and cards with fractional positions, labels, checklists and check items, card members and watchers, attachments and covers, power-ups, templates and an activity feed.

PostgreSQL
Media & content

Twitch live streaming database schema

How a live streaming platform models its data: broadcast sessions with start and end times, VODs and clips derived from them, tiered and gifted subscriptions, bits, chat, moderation logs and raids.

PostgreSQL
Social

Twitter (X) database schema

How a microblogging platform models its data: one tweets table covering tweets, replies, retweets and quotes, an asymmetric follow graph, a fanned-out home timeline, lists, bookmarks, and hashtags and mentions extracted at post time.

PostgreSQL
Travel

Uber ride-hailing database schema

How a ride-hailing app models its data: riders and drivers, vehicles and expiring documents, online sessions, ride requests, dispatch offers that time out, trips as a state machine, GPS pings, itemised fares with surge, and two-way ratings.

PostgreSQL
Developer tools

URL shortener & link analytics database schema

The classic system-design question, modelled properly: short codes from a base62 counter, custom aliases and custom domains, an append-only click log with daily rollups, expiry and click limits, QR codes and blocked-domain safety checks.

PostgreSQL
SaaS

Usage-based & metered billing database schema

Metered billing modelled properly: price plans built from components, tiered and volume and graduated pricing as rows, meters and raw usage, per-period aggregation, invoices with line items, prepaid credits, proration and dunning.

PostgreSQL
Fintech

Venmo-style peer-to-peer payments database schema

How a social payments app models its data: wallets and balances, linked bank accounts and cards, transfers between friends, payment requests, bill splits, per-payment privacy, and the feed with comments and likes.

PostgreSQL
Logistics

Warehouse & inventory management database schema

Bin-level inventory done properly: warehouses and storage locations, lot tracking for recalls, an append-only stock movement log with derived stock levels, purchase orders and outbound shipments.

PostgreSQL
Communication

WhatsApp messaging database schema

How a mobile messenger models its data: accounts keyed by phone number, linked devices, private contacts, direct and group chats as one entity, messages with media and replies, per-recipient delivery and read receipts, and disappearing messages with a TTL.

PostgreSQL
Media & content

YouTube video platform database schema

How a video platform models its data: channels and uploads, encoded renditions, view counts rolled up per day, likes, one-level comment threads, subscriptions, playlists, monetisation and community posts.

PostgreSQL
Communication

Zoom video meetings database schema

How a video meeting platform models its data: accounts and assigned licences, a meeting series separated from its materialised occurrences, registrations, participant join and leave intervals, breakout rooms, recordings, in-meeting chat and waiting room admissions.

other databases