Use it when designing tables or when data quality problems appear.
Schema, Keys & Data Types
Schema design defines tables, columns, data types, primary keys, foreign keys and constraints that keep data valid.
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.
schema → constraints enforced on every write → valid data
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 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.
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
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 · 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.
Subtopics
Go one level deeper into this subject.
A primary key uniquely identifies each row; a foreign key requires a value to exist in the referenced table.
Subtopic Choosing Data TypesThe column type decides what values are allowed, how much space they take and how comparisons and sorting behave.
Subtopic Schema MigrationsSchema migrations are versioned scripts that change tables in a controlled order so every environment has the same structure.
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).
\d <table>— first check for this topicpsql -c "SELECT now(), version();"— PostgreSQL reachable and versionmysql -e "SELECT NOW(), VERSION();"— MariaDB/MySQL reachable and versionsqlcmd -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.
| Element | Purpose |
|---|---|
| Data types | Store values efficiently and validate them (integer, numeric, text, timestamp with time zone, boolean, UUID, JSON) |
| Primary key | Unique, stable row identity |
| Foreign keys | Referential integrity between tables |
| NOT NULL, UNIQUE, CHECK | Enforce rules in the database |
| Default values | Consistent data when not supplied |
Practical guidance:
- Store timestamps with time zone (or always UTC), money as
numeric/decimalnot floating point, IP addresses in native types where available (inetin 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
ALTERlocks 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
- Primary and foreign keys
- Constraints
- NULL behavior
- Normalization concepts
- Common data types
- Schema-change implications
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Configuration & expected output
Concrete examples are shown only when the stored reference contains an actual configuration or output shape for this Topic.
Configuration example
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
\d ordersExpected 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.Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
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%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.
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.
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.
| Boundary | Inspect | Healthy interpretation | Do not infer |
|---|---|---|---|
| Intent | Primary and foreign keys | Intended object/scope is explicit and versioned where relevant | Intent is already effective |
| Owning runtime/control plane | Constraints / NULL behavior | Owner accepts and reports the expected object state | Downstream dependencies are healthy |
| Effective state | Normalization concepts | Independent read-back matches the intended state | Every client sees the same result |
| Consumer outcome | Common data types | The original bounded check succeeds in the same time window | Production correctness outside this scope |
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.