Design a SQL database well by starting from the questions the data must answer, then translating those into normalized tables, keys, constraints, and indexes before you tune anything for speed. The key condition is requirements first: if you cannot name your entities, their relationships, and the queries that matter, later schema choices become guesswork. A sound design makes invalid states hard to store, keeps each fact in one place, and stays affordable to change as the application grows. The practices below follow that order—model the domain, enforce integrity, choose types carefully, index for real queries, plan transactions and concurrency, then evolve the schema with migrations.
Start With Workload and Domain Discovery
Schema quality is judged against a workload. Before writing a CREATE TABLE statement, write down three things: the entities the business cares about, the relationships between them, and the twenty or so queries that will dominate traffic. This is not bureaucracy; it is the only way to know whether a design is finished. An order system for a small shop and a ledger for a bank look similar in an entity diagram and completely different in constraint and transaction design.
For each entity, list its identity, its attributes, and the rules that must always hold. "An invoice belongs to exactly one customer" is a relationship with a cardinality. "An order line's quantity is greater than zero" is a check constraint. "A SKU code is unique across the catalog" is a uniqueness rule. Collect these as business rules now, because each one either becomes a database constraint or becomes a bug waiting in application code.
Queries deserve equal weight. A design that supports SELECT * FROM orders WHERE customer_id = ? ORDER BY created_at DESC LIMIT 20 efficiently may need a different index than one that aggregates monthly revenue by region. Note access patterns, expected row counts, read/write ratio, and whether data is append-only or heavily updated. Rough volume estimates are enough at this stage—orders of magnitude guide decisions about partitioning and index strategy later.
Finally, identify lifecycle needs: retention periods, soft-delete requirements, audit trails, and multi-tenancy. These shape the schema more than most beginners expect. A tenant column added later can force painful rewrites; a delete flag that hides rows can silently break unique constraints.
Model Entities and Relationships Before Writing Tables
The relational model's central promise is that each fact is stored once. Pursuing that promise means starting normalized—typically to third normal form (3NF)—and denormalizing deliberately afterward for measured reasons. The practical translation is simple: one table per entity, foreign keys for relationships, and no repeating groups crammed into a single column.
Consider a store: customers, orders, and order_items. Putting product names and prices directly on the orders table duplicates data per line and makes updates inconsistent. The normalized shape stores product facts in products and puts a reference to the product in order_items, with quantity and the price charged at purchase time. Note the nuance: the price charged is a fact about the order line, not about the product, so it belongs on order_items even though it looks like duplication. Copying a value is correct when it captures a moment in time; copying it to avoid a join is not.
Choose between one-to-many, many-to-many, and one-to-one relationships explicitly. Many-to-many needs a junction table, such as product_tags(product_id, tag_id), with a composite primary key or a surrogate key plus a unique constraint on the pair. One-to-one often signals an optional detail block or a table split for large columns; use it sparingly, and enforce it with a unique foreign key.
Then decide on keys. Surrogate keys—integers or UUIDs generated by the system—are stable and compact for joins. Natural keys such as email addresses or ISBNs carry business meaning but change, so prefer them as unique constraints rather than primary keys. Composite primary keys are legitimate for junction tables and for tables whose identity genuinely is the pair of foreign keys.
Resist the urge to model every possible future attribute. A schema with forty nullable columns "just in case" obscures what is actually required and invites inconsistent data. Add columns when the requirement exists, not before.
Normalize to 3NF, Then Denormalize With Intent
Normalization reduces update anomalies: if a customer's address lives in five places, changing it means finding and updating all five, and missing one produces contradictory records. First normal form removes repeating groups and ensures atomic column values. Second normal form removes partial dependencies on part of a composite key. Third normal form removes transitive dependencies—non-key columns that depend on other non-key columns rather than on the key.
A common violation is storing city, state, and postal_code with a derived shipping_region that depends on the postal code. The region is a function of another non-key attribute. Either compute it at query time or move postal-code-to-region mapping into its own reference table. Similar cases include storing total_price alongside line items when it is always the sum of them, or storing age when birth_date exists.
Denormalization is a legitimate performance tool, but it should follow measurement. Caching an aggregate count on a parent row, storing a materialized total, or duplicating a display name for read speed all create the obligation to keep copies in sync. Name the mechanism: database triggers, application transactions, or a scheduled job. If no mechanism exists, you have introduced a future inconsistency. For reporting, prefer views or materialized views over denormalized base tables, because views centralize the definition and can be changed without rewriting stored data.
A middle ground that often works: keep the base schema normalized and add indexes or summary tables that can be rebuilt. Any derived data that can be regenerated from source tables is far safer than derived data that is the only copy.
Enforce Integrity With Keys, Constraints, and Types
The database should reject invalid states, not merely hope the application avoids them. Constraints are the cheapest form of correctness because they cannot be bypassed by a different client, a script, or a future developer.
Primary keys guarantee row identity; every table should have one. Foreign keys guarantee referential integrity—an order line cannot reference a nonexistent product. Use ON DELETE behavior deliberately: RESTRICT or no action protects parent rows, CASCADE deletes children automatically, and SET NULL preserves children without a parent. Cascades are convenient but dangerous in wide graphs; make sure deleting a customer does not silently delete financial records that must be retained.
Unique constraints prevent duplicate business facts, such as two accounts with the same email or two active subscriptions per user. Where partial uniqueness is needed—one active subscription, many canceled ones—a partial unique index (supported in PostgreSQL and SQL Server via filtered indexes) expresses the rule directly.
Check constraints handle range and format rules that are stable and local to one row: quantity greater than zero, status in an allowed set, end date after start date. NOT NULL is itself a constraint and one of the most valuable; defaulting to nullable everywhere forces every consumer to handle missing values. Add NOT NULL when the business rule says a value must exist.
Data types matter as much as constraints. Use a date type for dates, a timestamp with time zone for moments in time, a numeric or decimal type for money rather than floating point, and a boolean for flags. Store money as integer minor units or exact decimal; binary floating point cannot represent most decimal fractions exactly, and rounding errors compound across sums. Choose the smallest type that safely covers realistic values, and avoid generic text columns for identifiers that are actually integers or UUIDs.
Choose Data Types and Naming for the Long Run
Naming is documentation that never goes out of date. Pick one convention and apply it without exception: snake_case for tables and columns is common and portable; table names plural (orders) or singular (order) both work, but mixing them creates friction. Name primary keys consistently (id or order_id), and name foreign keys after the referenced table (customer_id). Avoid reserved words and cryptic abbreviations.
Primary key type is a real trade-off. Auto-incrementing 64-bit integers are compact, fast, and naturally ordered, which helps index locality. UUIDs are globally unique and enable client-side ID generation, but random UUIDv4 values scatter index inserts and enlarge indexes. If you need UUIDs, consider time-ordered variants (UUIDv7 or a database-specific sequential UUID function) to recover locality. The choice changes real performance at scale, so decide early and be consistent.
Timestamps deserve explicit treatment. Store moments as timestamp with time zone (or the equivalent) and let the database normalize to UTC; store civil dates—birthdays, business dates—as plain dates without time. In MySQL, TIMESTAMP and DATETIME differ in range and time-zone handling; check the version's behavior before relying on it. For event tables, include a created timestamp by default and, where relevant, an updated timestamp maintained by the application or a trigger.
Character types: use variable-length text with a sensible limit or none, and avoid fixed-length padding types unless the domain is truly fixed-width. Length limits are constraints, so set them at the business maximum, not at an arbitrary 255.
Index for Real Queries, Not for Every Column
Indexes speed reads and slow writes. Each index must earn its cost by supporting a query pattern you actually have. The starting point is the workload list from discovery: for each important query, identify the filter columns, join columns, and sort order.
Composite index column order matters. An index on (customer_id, created_at) supports filtering by customer and sorting by creation time. The same index generally cannot efficiently serve a query filtering only on created_at, because the leading column is missing. Put equality-filter columns first and range or sort columns after them. Covering indexes that include all columns a query needs can avoid table lookups, but they widen indexes and increase write cost.
Foreign keys are not automatically indexed in PostgreSQL and MySQL's InnoDB; in SQL Server, they are not indexed automatically either. A missing index on a referencing column makes parent deletes and joins slow, so index every foreign key unless a composite index already covers it as a leading column.
Watch out for indexing pitfalls. Functions on indexed columns, like WHERE lower(email) = ?, prevent ordinary index use unless you create an expression index or store a normalized column. Leading wildcards (LIKE '%term') cannot use a B-tree index efficiently. Low-cardinality flags make poor standalone indexes. And redundant indexes—one on (a) and one on (a, b) when only the latter is needed—waste write throughput.
Measure before adding. Use the query plan (EXPLAIN, EXPLAIN ANALYZE, or the vendor's equivalent) with realistic data volumes. A design that looks fine on a thousand rows can collapse on ten million. Also avoid premature partitioning; it adds complexity and is usually a response to measured table size and maintenance pain, not a default.
Design Transactions and Concurrency Deliberately
Transactions define what must be atomic. A transfer between two accounts must debit and credit together or not at all. An order with line items should insert the parent and children in one transaction so partial orders never appear. Write these units down as part of the design, because they constrain where data can live and how services call the database.
Choose an isolation level with your eyes open. Most databases default to read committed (PostgreSQL, Oracle, SQL Server) or repeatable read (MySQL InnoDB). Higher isolation reduces anomalies but increases contention and retries. Understand the specific anomaly you need to prevent: lost updates, write skew, phantom reads. For counter-style updates, prefer atomic statements (UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?) over read-modify-write in application code.
Keep transactions short. Long transactions hold locks, bloat undo or version storage, and increase deadlock probability. Do external calls—HTTP requests, file uploads—outside the transaction boundary. Acquire locks in a consistent order across code paths to reduce deadlocks, and build retry logic for deadlock and serialization failures where the database reports them.
For high-concurrency counters and queues, design for contention explicitly: separate hot rows, use append-only event tables, or batch updates. Optimistic concurrency with a version column is a clean pattern for editable records; include the version in the update's WHERE clause and treat zero affected rows as a conflict.
Plan Migrations, Access Control, and Multi-Tenancy Up Front
Schemas change. A design that assumes immutability will fail in production. Adopt versioned migrations from day one: every change is a script checked into source control, applied in order, and tested against a copy of realistic data. Favor backward-compatible changes in three steps—add the new column nullable, backfill, then enforce NOT NULL and drop the old column—so running application versions never break.
Access control is part of design. Grant the application the minimum privileges it needs; separate read-only reporting users from write users; avoid using a superuser account in application configuration. For multi-tenant systems, decide between a shared table with a tenant column, schema-per-tenant, and database-per-tenant. Shared tables are simplest and cheapest but require every query to filter by tenant and every unique constraint to include the tenant column; stronger isolation costs more operationally. This decision changes indexes and constraints, so make it before launch.
Backups and recovery belong to design too. Know your recovery point and recovery time objectives, and verify restores, not just backup jobs. A schema that cannot be restored within the business's tolerance is not finished.
Validate the Design With a Checklist and a Small Test
Before committing, walk through a concrete validation pass. This is a review procedure, not a build step, and it catches most expensive mistakes.
Prerequisites: the entity list, business rules, top queries, and volume estimates from discovery. Then:
1: Draw the tables and relationships and confirm every many-to-many has a junction table and every relationship has a foreign key. 2: For each business rule, write the constraint that enforces it; if a rule cannot be enforced in the database, document where it is enforced in code. 3: Check every table has a primary key, every required column is NOT NULL, and every foreign key column is indexed. 4: For each top query, write the intended index and confirm the leading columns match its filters and sort. Run EXPLAIN on a test dataset with representative row counts. 5: Insert deliberately invalid rows and confirm the database rejects them—negative quantity, duplicate email, orphaned child, null required field. If any insert succeeds, the constraint is missing. 6: Simulate a schema change you expect within a year and draft the migration steps. If the change requires rewriting a huge table or breaking running clients, revisit the model.
Stop condition: if validation reveals that critical business rules cannot be expressed as constraints, or that query patterns require a fundamentally different data model (for example, graph traversal or full-text search dominating), bring in a data architect or senior database engineer before building further. Continuing to bolt constraints and indexes onto an unsuited model multiplies cost.
Common Failure Modes and How Good Designs Avoid Them
Most real-world schema pain comes from a short list. Storing multiple values in one column—comma-separated IDs, JSON blobs used as tables—defeats joins, constraints, and indexes unless the database's JSON support is genuinely appropriate and queried with expression indexes. The fix is proper child tables or, when JSON is justified, documented query patterns.
Missing foreign keys are another frequent failure: the application "always checks," until a bug, a bulk import, or a manual script bypasses it, leaving orphaned rows. Money stored as floating point produces reconcilable-today, wrong-tomorrow totals. Timestamps stored as strings break range queries and time-zone conversion. Nullable columns that are semantically required force every reader to guess. And schemas with no migration discipline drift between environments until no one can reproduce production.
The countermeasures are unglamorous: constraints, consistent types, versioned migrations, indexes tied to queries, and short transactions. None of them requires advanced tooling, and together they carry most of the quality.
What Changes With Scale, Vendor, and Version
The core practices hold across PostgreSQL, MySQL, SQL Server, Oracle, and SQLite, but specifics differ. JSON support ranges from excellent (PostgreSQL jsonb with GIN indexes) to workable to limited; check your version before designing around it. Partial and expression indexes exist in PostgreSQL and SQL Server (filtered and computed-column indexes), while MySQL lacks partial indexes, so uniqueness rules need alternative modeling. MySQL's default isolation differs from PostgreSQL's, which changes concurrency behavior. ON CONFLICT/ON DUPLICATE KEY/MERGE syntax varies, so upsert logic must be written per vendor.
Scale changes emphasis rather than principles. At large volumes, consider partitioning by time or tenant, archive cold rows, and be stricter about index count and bloat. At small volumes, simplicity wins; a three-table schema with correct constraints beats a distributed design no one can operate. Right-size the design to the workload you measured, and revisit when the workload changes.
If you take one practice from this guide, make it constraint-driven modeling: write down the rules, encode them in keys, foreign keys, checks, and types, and let the database enforce them. Performance tuning is iterative and reversible; a schema that permits invalid data is neither.