Pcornel
Browse topics
Options
Recent
Favorites
Databases · Technical reference

Schema, Keys & Data Types

Direct answer

Schema design defines tables, columns, data types, primary keys, foreign keys and constraints that keep data valid.

When to use this

Use it when designing tables or when data quality problems appear.

First 30 seconds

1. Describe the table: \d <table> (psql) / SHOW CREATE TABLE <t>; / sp_help <t>.

2. Primary key present?

3. Foreign keys and indexes on FK columns?

4. Constraints for valid values.

5. Types appropriate.

Operational verification

schema → constraints enforced on every write → valid data

Evidence · next step

Common problems are weak/missing keys, unexpected NULL semantics, lossy numeric/string conversions, incompatible collations/encodings, foreign-key failures from orphaned data and schema changes that rewrite large tables or block traffic. Preserve the first divergent observation and repeat the same bounded verification after remediation.

Continue only after interpreting the current observation.
Context & applicabilityCommon mistakes · platform/version boundaries
Common mistakes
What not to infer

Common problems are weak/missing keys, unexpected NULL semantics, lossy numeric/string conversions, incompatible collations/encodings, foreign-key failures from orphaned data and schema changes that rewrite large tables or block traffic.

Databases owns logical schema and engine enforcement. Application teams own domain modeling choices; Storage owns physical media and filesystem behavior.

Platform / version applicability
MariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformMariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts · Databases owns logical schema and engine enforcement. Application teams own domain modeling choices; Storage owns physical media and filesystem behavior.
Scope / prerequisiteUse it when designing tables or when data quality problems appear.
What next?3 suggested next steps
Child topics (this level)3
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

2 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

Capture the concrete output, symptom, packet, log or counter before changing anything.

Step 1 Verification workflow Verify boundary

Inspect the actual schema definition, key/constraint state and column types before changing application assumptions. For a schema change, test existing data compatibility, lock/rewrite behavior and dependent indexes/queries, then verify constraints and representative application operations after deployment.

Step 2 Failure signatures and limits Narrow the fault

Common problems are weak/missing keys, unexpected NULL semantics, lossy numeric/string conversions, incompatible collations/encodings, foreign-key failures from orphaned data and schema changes that rewrite large tables or block traffic.

Evidence references

Evidence · 1 on this Topic

Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.

test · 1
Drill down

Subtopics

Go one level deeper into this subject.

Key points

Every table needs a primary key. Use foreign keys and NOT NULL/CHECK constraints to let the database enforce rules. Choose types that fit the data (not text for everything).

Key checks
  • \d <table> — first check for this topic
  • psql -c "SELECT now(), version();" — PostgreSQL reachable and version
  • mysql -e "SELECT NOW(), VERSION();" — MariaDB/MySQL reachable and version
  • sqlcmd -S <server> -Q "SELECT @@VERSION" — SQL Server reachable and version
ReferenceWhat it is1 section · depth on demand

Operating model

Schema, Keys & Data Types covers how a relational schema encodes identity, relationships, allowed values and storage/semantic choices. Keys and constraints are integrity mechanisms; data types influence comparison, range, precision, encoding and index behavior; NULL represents missing/unknown state rather than a normal value.

ReferenceHow it works1 section · depth on demand

In depth

The schema defines tables, columns, data types, keys and constraints — the rules that keep data correct. Good schema design prevents bad data at the source; changing a schema later on a large production table can be slow and risky.

ElementPurpose
Data typesStore values efficiently and validate them (integer, numeric, text, timestamp with time zone, boolean, UUID, JSON)
Primary keyUnique, stable row identity
Foreign keysReferential integrity between tables
NOT NULL, UNIQUE, CHECKEnforce rules in the database
Default valuesConsistent data when not supplied

Practical guidance:

  • Store timestamps with time zone (or always UTC), money as numeric/decimal not floating point, IP addresses in native types where available (inet in PostgreSQL).
  • Index foreign key columns used in joins.
  • Apply schema changes through migration tools (Flyway, Liquibase, Alembic, framework migrations) in version control.
  • For large tables, check whether an ALTER locks the table and use online methods (PostgreSQL concurrent operations, MySQL online DDL, gh-ost/pt-online-schema-change).
ReferenceImportant terms & boundaries1 section · depth on demand

Scope map

Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Technical examples

Configuration & expected output

Concrete examples are shown only when the stored reference contains an actual configuration or output shape for this Topic.

Configuration example

SQL (PostgreSQL syntax) PostgreSQL 14 or laterTable with primary key, foreign key, NOT NULL and a CHECK constraint.

Assumptions: Table customers(id) exists.

CREATE TABLE orders (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id bigint NOT NULL REFERENCES customers(id),
  total_cents integer NOT NULL CHECK (total_cents >= 0),
  created_at  timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX orders_customer_id_idx ON orders (customer_id);

Expected output

SQL (PostgreSQL syntax) PostgreSQL 14 or later\d orders

Expected state: Columns, constraints and the foreign-key index appear as designed.

Table "public.orders"
   Column    |           Type           | Nullable |           Default
-------------+--------------------------+----------+------------------------------
 id          | bigint                   | not null | generated always as identity
 customer_id | bigint                   | not null |
 total_cents | integer                  | not null |
 created_at  | timestamp with time zone | not null | now()
Indexes:
    "orders_pkey" PRIMARY KEY, btree (id)
    "orders_customer_id_idx" btree (customer_id)
Check constraints:
    "orders_total_cents_check" CHECK (total_cents >= 0)
Foreign-key constraints:
    "orders_customer_id_fkey" FOREIGN KEY (customer_id) REFERENCES customers(id)
PostgreSQL does not index foreign-key columns automatically; without the extra index, deletes on customers scan orders. Illustrative authored output: field layout matches the tool, values will differ in your environment.
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-29 · otherMariaDB / PostgreSQL / Microsoft SQL Server concepts PostgreSQL current documentation

Documentation verification: confirms the upstream model used by the Topic. It does not assert local production behavior.

Basis: https://www.postgresql.org/docs/current/ddl.html · confidence 92%
Technical changelog & impact

What changed and what may be affected

Recent technical edits are separated from ordinary page timestamps. Relationship impact is advisory: it identifies nearby canonical references to review, not automatic breakage.

Related reference impactReview these references after material technical changes when their shared boundary is affected.
Terminology layer

Terms & aliases

Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.

Aliases that resolve here
schema, keys & data typesdatabase schema keysprimary foreign keydatabase data types
Embedded reference data

Quick lookup tables

Schema, Keys & Data Types verification boundary matrix

A compact lookup separating intent, owning component state, effective state and consumer-visible outcome for Schema, Keys & Data Types.

BoundaryInspectHealthy interpretationDo not infer
IntentPrimary and foreign keysIntended object/scope is explicit and versioned where relevantIntent is already effective
Owning runtime/control planeConstraints / NULL behaviorOwner accepts and reports the expected object stateDownstream dependencies are healthy
Effective stateNormalization conceptsIndependent read-back matches the intended stateEvery client sees the same result
Consumer outcomeCommon data typesThe original bounded check succeeds in the same time windowProduction correctness outside this scope
Depth when you need it

Deep reference

Design & tradeoffs

Scope

Databases owns logical schema and engine enforcement. Application teams own domain modeling choices; Storage owns physical media and filesystem behavior.

Confirmation

Confirm action

Continue?