Schema Design, Normalization & Data Types
"There is, in fact, a very simple elimination procedure, which we shall call normalization." — E. F. Codd, A Relational Model of Data for Large Shared Data Banks, Communications of the ACM, June 1970
Summary: A schema is a set of promises the database enforces against every writer: each fact stored once (normalization), each value of the right type, each rule a constraint. Focus: Functional dependencies and 1NF to BCNF (4NF/5NF briefly), deliberate denormalization, key choice, constraints, the data types that bite (time, money, text, JSONB), and how Go and Laravel map them. Learning goal: Take a messy table, normalize it to 3NF, pick keys and types with reasons, denormalize one read path safely, and measure that it paid off.
This page is the complete reference for relational schema design: the theory (functional dependencies, candidate keys, normal forms and the anomalies they remove), the practice (denormalization strategies, surrogate vs natural keys, bigint identity vs UUIDv4 vs UUIDv7/ULID, composite keys, foreign keys and their ON DELETE/ON UPDATE actions, deferrable constraints, CHECK and EXCLUDE), the modelling patterns people argue about (enums vs lookup tables, polymorphic associations, EAV, JSONB, arrays, ranges, soft deletes, audit columns), the data types that cause production incidents (timestamptz, numeric, text, citext, inet), and the product differences between PostgreSQL, MySQL/InnoDB, SQL Server, Oracle, SQLite, MongoDB, CockroachDB and Redis. Sibling pages hold the neighbouring detail: ID Generation at Scale for how IDs are produced, Zero-Downtime Schema Migrations for changing a live schema, Multi-Tenancy Strategies for tenant isolation, Partitioning & Sharding in PostgreSQL for splitting tables, Indexing for what an index costs, and Isolation Levels for concurrent writers.
Page map
| If you are looking for | Go to |
|---|---|
| The tables you can memorise in one minute | Everything in one minute |
| Why a schema is a set of enforced promises | Why schema design matters |
| Where normalization comes from (Codd 1970) | Where it comes from |
| Determinants, candidate keys, closure | Functional dependencies and keys |
| 1NF, 2NF, 3NF, BCNF, 4NF, 5NF and the anomalies | The normal forms, one by one |
| Materialized views, counter caches, triggers, application copies | Denormalization |
| Surrogate vs natural, bigint vs UUID vs ULID, composite keys | Keys |
Foreign keys, ON DELETE, deferrable, CHECK, EXCLUDE, NOT NULL, NULL logic | Constraints |
| Enums, polymorphic associations, EAV, JSONB, arrays, ranges, soft deletes, audit columns, tenant columns | Modelling patterns |
timestamptz, numeric, text, citext, boolean, inet, generated and identity columns | Data types |
| PostgreSQL vs MySQL vs SQL Server vs Oracle vs SQLite per feature | Per-engine behaviour |
| Error codes, naming, partitioning hint, storage details | Mechanics |
Go sql.Null*, Laravel migrations and casts, Eloquent conventions | Solving the classic problems |
| Which design for which situation | Choosing |
| Monolith to microservices to distributed data | In architecture |
| Normalize a CSV, then denormalize and measure | Lab |
| Wrong beliefs, cheat sheet, every term defined | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The normal forms. Each row is unpacked in the normal forms section.
| Form | Rule in plain words | Tiny violation | What it removes |
|---|---|---|---|
| 1NF | One atomic value per cell, rows identifiable | product_ids = "P1;P2" | Lists and repeating groups |
| 2NF | Non-key columns depend on the whole key | product_name in order_lines(order_id, product_id, ...) | Partial dependencies |
| 3NF | Non-key columns depend on nothing but the key | customer_city determined by customer_email on an order | Transitive dependencies |
| BCNF | Every determinant is a candidate key | (student, course) -> teacher and teacher -> course | Anomalies with overlapping keys |
| 4NF | No independent multi-valued facts in one table | employee, skill, language | Row explosion from MVDs |
| 5NF | No join dependency that is not implied by keys | Supplier-part-project triple | Lossless-join redundancy |
The keys.
| Choice | Size | Insert locality | Guessable | Typical use |
|---|---|---|---|---|
bigint identity | 8 bytes | Right edge of the B-tree | Yes (sequential) | Default internal key |
| UUIDv4 | 16 bytes | Random: scattered inserts | No | Client-generated IDs, security through obscurity is not a goal |
| UUIDv7 / ULID | 16 bytes (ULID text is 26 chars) | Time-ordered: near right edge | Partly (timestamp leaks) | Distributed writers, public IDs |
| Natural key | Varies | Varies | Yes | Reference data (ISO country codes) |
| Composite key | Sum of parts | Depends on leading column | Yes | Join tables, per-tenant uniqueness |
The types that bite.
| Do not | Why | Use instead |
|---|---|---|
timestamp for instants | It is "a picture of a calendar and a clock", no zone | timestamptz |
float / money for money | Binary rounding; money has no currency | numeric(12,2) or integer minor units plus a currency column |
varchar(255) by habit | No performance gain in PostgreSQL | text plus CHECK where a real limit exists |
NOT IN (subquery) | One NULL makes it return nothing | NOT EXISTS |
BETWEEN on timestamps | Closed interval includes the upper bound | >= a AND < b |
serial for new tables | Odd dependency and permission behaviour | GENERATED ALWAYS AS IDENTITY |
The three things to do.
| Situation | Do this |
|---|---|
| New table | Surrogate key, natural key as UNIQUE, NOT NULL by default, foreign keys, CHECK for domain rules, timestamptz |
| Slow read of a derived value | Measure first, then add one derived copy with one refresh mechanism and a drift query |
| Unsure whether a column should be JSONB | If you filter, join or constrain on it in every query, it is a column |
Why schema design matters
Application code is rewritten every few years; the tables remain. Every row ever written has to satisfy the schema of the day, and every service, script and analyst query reads it. A schema is the one place a rule holds against every writer, which application code cannot promise.
| Looser (fewer constraints, denormalized, JSON everywhere) | Stricter (normalized, typed, constrained) |
|---|---|
| Fast to start, no migrations for new fields | Slower to start, every change is a migration |
| Each fact may exist many times and drift | Each fact exists once; one UPDATE fixes it |
| Bugs surface in reports months later | Bugs surface as an error at write time |
| Cheap reads of a pre-joined shape | Joins on every read (but planners are good at joins) |
| The application must enforce every rule | The database refuses invalid states even from a script |
An everyday picture. A shop writes the customer's address on a sticky note stuck to every receipt. When the customer moves, someone has to find every receipt. Normalization is one address card in a drawer with receipts pointing at it. The one exception is the receipt itself: a copy of the address as it was on the day is exactly what you want to keep.
Three common misunderstandings, up front
- "Normalize to 3NF always." Normalization removes anomalies; it does not promise speed. A measured read cost can justify one deliberate copy, as long as one mechanism keeps it honest.
- "The ORM or the application validates it, so the database does not need constraints." The application is one writer among many (migrations, scripts, other services, a tired engineer in
psql). Only constraints hold against all of them, and only the database can enforce them under concurrency. - "
jsonbmeans no schema." It means the schema moved into application code, where nothing checks it. If a key is queried on every request, it is a column that lost its type,NOT NULLand foreign key.
Where it comes from
Normalization starts in the 1970 paper that introduced the relational model. Codd's "normal form" there is narrow: a relation whose domains are all simple, meaning no cell holds another relation. He shows how an employee that contains jobhistory and children flattens into four relations, each carrying its parent's key, and gives the practical reason:
"The simplicity of the array representation which becomes feasible when all relations are cast in normal form is not only an advantage for storage purposes but also for communication of bulk data between systems which use widely different representations of the data."
He then adds: "Further operations of a normalizing kind are possible. These are not discussed in this paper." Those further operations became second and third normal form in Codd's 1971 follow-up and Boyce-Codd normal form a few years later. I did not find a readable copy of either, so the definitions below are the textbook ones, not quotations. The 4NF (Fagin, 1977) and 5NF (project-join normal form, Fagin, 1979) attributions are likewise from the textbook literature, not from a source saved for this page.
The data-type half of the topic has a different source: the PostgreSQL manual and the community "Don't Do This" wiki page, which record what actually goes wrong in production.
Functional dependencies and keys
Everything in normalization rests on one idea, so it is worth making precise before the forms.
Functional dependency Must-know
In plain words: column A determines column B when knowing A tells you B for certain. An email address determines the name on the account; an order id determines the order date.
Common misunderstanding: "A functional dependency is something I can see in the current rows." It is a rule about the business, not about the data you happen to have. If all your customers currently live in different cities, city -> customer still does not hold. You discover FDs by asking the domain, then check them against data (a query that finds counter-examples), never the other way round.
Definition: in a relation R, the set of attributes X functionally determines Y (written X -> Y) when every pair of rows that agree on X also agree on Y. X is the determinant.
orders_flat (the lab's table)
order_id -> order_date, customer_email -- one order has one date and one customer
customer_email -> customer_name, customer_city -- one email is one customer
customer_city -> customer_country -- a city (in our data) is in one country
product_id -> product_name -- one product has one name
(order_id, product_id) -> qty, unit_price -- the line itselfReal scenario: a CSV export from an old system has 40 columns. Listing the FDs on a whiteboard is the whole design: each determinant that is not the key marks a table waiting to be split out.
Finding counter-examples: a query that tests a suspected FD returns the rows that break it.
-- Does customer_email determine customer_city? Any row returned breaks the dependency.
SELECT customer_email, count(DISTINCT customer_city) AS cities
FROM orders_flat
GROUP BY customer_email
HAVING count(DISTINCT customer_city) > 1;Keys: superkey, candidate key, primary key, prime attribute Must-know
In plain words: a key is a set of columns that identifies a row. A candidate key is a smallest such set; one candidate is chosen as the primary key.
Common misunderstanding: "The primary key is the only key." A table can have several candidate keys (id, email, (tenant_id, slug)), and all of them should be declared UNIQUE or PRIMARY KEY. The unchosen ones are called alternate keys, and they are the natural keys of the table.
Definition: a superkey is any attribute set whose values are unique across rows; a candidate key is a superkey with no unnecessary column; a prime attribute is one that belongs to some candidate key. The closure X+ of a set X is every attribute X determines (directly or by chaining FDs); X is a superkey exactly when X+ is every column.
Real scenario: order_lines(order_id, product_id, qty): (order_id, product_id) is the only candidate key, so both columns are prime and qty is not. This is what 2NF and 3NF talk about.
The normal forms, one by one
The picture shows the lab's example in four stages. The sections below take the same table through each rule.
The anomalies Must-know
In plain words: the same fact stored in several rows will, sooner or later, disagree with itself. There are three ways it bites, and every normal form exists to close one of them.
Common misunderstanding: "Duplicated data only wastes disk." The cost is correctness: a table that contradicts itself cannot say which answer is true.
Definition: an update anomaly is a change that must be repeated in many rows and is applied to only some; an insert anomaly is a fact that cannot be recorded without an unrelated fact; a delete anomaly is the loss of a fact that happened to ride along with another one.
Session 1 (support) Session 2 (reporting)
1 -- orders_flat has 10 rows for ada@example.com, city = 'London'
2 UPDATE orders_flat SET customer_city = 'Paris'
WHERE order_id IN (1001, 1003, 1010); -- 3 of 10 rows, the app only knew about 3
3 SELECT customer_city, count(*) FROM orders_flat
WHERE customer_email = 'ada@example.com' GROUP BY 1;
4 -- Paris 3, London 7: where does Ada live?| Anomaly | Example in the flat orders_flat table | Which form removes it |
|---|---|---|
| Update | A customer moves; you update 9 of their 10 orders and the table disagrees with itself | 3NF (city lives in one row of customers) |
| Insert | You cannot record a product until someone orders it | 2NF (products is its own table) |
| Delete | Deleting a customer's only order deletes the only copy of their address | 3NF |
Real scenarios: two spellings of the same city in a report; a product renamed on 11 of 12 order lines; an address lost with the last order of a closed account.
What prevents it: normalization removes the duplication; a UNIQUE or foreign key constraint makes the single copy the only copy.
Fix / how to use it: the lab below normalizes orders_flat and shows the update anomaly disappearing (one UPDATE, one row).
1NF: atomic values Must-know
In plain words: each cell holds one value, not a list, and each row can be told apart from every other.
Common misunderstanding: "A jsonb or array column is automatically a 1NF violation." In the strict relational sense it is, because the cell holds a collection; in practice PostgreSQL arrays and jsonb are legitimate when the collection is only ever stored and returned whole, never joined or constrained element by element. The rule is a design smell detector, not a prohibition. Codd's 1970 rule is the older, stricter one: every domain simple.
Definition: a relation is in 1NF when every attribute is atomic and there is no repeating group (phone1, phone2, phone3), and every row is identifiable (a key exists).
Raw CSV row After 1NF
order_id | product_ids | qty_list order_id | product_id | qty
1001 | "P1;P2" | "1;2" 1001 | P1 | 1
1001 | P2 | 2Real scenarios: comma-separated tag columns; phone1..phone3; a status_history text column appended to on every change; a CSV import with ;-separated cells.
What prevents it: nothing in the database stops you from writing "P1;P2" into a text column; this is a design decision, and the first one.
Fix: split into a child table (SQL), read it as rows (Go), and model it with a relationship (Laravel).
CREATE TABLE order_lines (
order_id bigint NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
product_id text NOT NULL REFERENCES products (id) ON DELETE RESTRICT,
qty integer NOT NULL CHECK (qty > 0),
PRIMARY KEY (order_id, product_id)
);// Each line is a row, so aggregation is SQL, not string splitting in Go.
rows, err := db.QueryContext(ctx,
`SELECT product_id, qty FROM order_lines WHERE order_id = $1`, orderID)// Order hasMany OrderLine: one query, no explode(';', ...).
$order->lines()->where('qty', '>', 1)->get();2NF: the whole key Must-know
In plain words: if the key has two columns, every other column must depend on both, not on just one of them.
Common misunderstanding: "2NF matters for every table." It can only be violated when the key is composite; a table with a single-column key is always in 2NF if it is in 1NF.
Definition: a relation is in 2NF when it is in 1NF and no non-prime attribute is functionally dependent on a proper subset of any candidate key.
order_lines(order_id, product_id, product_name, qty) PK (order_id, product_id)
product_id -> product_name -- depends on HALF the key: violation
order_id -> order_date -- also half the key, if order_date is in this table
Split: products(id, name) orders(id, order_date) order_lines(order_id, product_id, qty)Real scenarios: a product name repeated on every order line; a course title repeated on every enrolment; an invoice currency repeated on every invoice line.
What prevents it: the split itself plus a foreign key from order_lines.product_id to products.id.
Fix: the diagram and the lab show the split; the SQL for the three tables is in the lab.
3NF: nothing but the key Must-know
In plain words: every non-key column must describe the key, the whole key and nothing but the key (the mnemonic is a joke on a court oath; the idea is real).
Common misunderstanding: "3NF means every value in its own table." Only columns determined by another non-key column move. A status text column that depends on nothing else stays.
Definition: a relation is in 3NF when it is in 2NF and every non-prime attribute depends directly on a candidate key, never through another non-key attribute. Equivalent form: for every FD X -> A, either X is a superkey or A is a prime attribute.
orders(id, customer_id, customer_city, customer_country)
id -> customer_id -> customer_city -> customer_country -- transitive chain
Split: orders(id, customer_id) customers(id, email, name, city_id) cities(id, name, country_code)Real scenarios: an employee row with department_id and department_name; a shipment row with warehouse_id and warehouse_address; a postal code and the city it implies.
What prevents it: foreign keys from the child to the single table that owns the fact.
Fix: same split as above; a snapshot column (the address at the time) is the one legitimate exception, see denormalization.
BCNF Important
In plain words: 3NF has a loophole when a table has two overlapping candidate keys. Boyce-Codd normal form closes it by demanding that every determinant be a candidate key.
Common misunderstanding: "If it is in 3NF it is in BCNF." They differ only when candidate keys overlap. Many tables are in both; the textbook counter-example is below.
Definition: a relation is in BCNF when, for every non-trivial FD X -> Y, X is a superkey.
enrolment(student, course, teacher) rule: each teacher teaches one course
FDs: (student, course) -> teacher teacher -> course
Candidate keys: (student, course) and (student, teacher) -- all attributes are prime, so 3NF holds
teacher -> course violates BCNF (teacher is not a key)
Split: teaches(teacher, course) attends(student, teacher)Real scenario: a booking table where a room belongs to one building and (room, slot) and (person, slot) are both unique; a course roster where each instructor owns exactly one course.
Trade-off: the split can lose the ability to enforce (student, course) -> teacher with one constraint (the dependency is no longer inside one table). That is why textbooks say 3NF always keeps dependencies and BCNF may not.
Fix: split as shown and add a UNIQUE (teacher) on teaches(teacher, course) so a teacher cannot appear twice.
4NF and 5NF, briefly Good to know
In plain words: 4NF is about two independent lists living in one table; 5NF is about a three-way fact that is really three two-way facts.
Common misunderstanding: "I need to check 4NF and 5NF on every table." In practice, if your tables are BCNF and each represents one kind of fact, you almost never violate them. They matter when you see a table whose row count is the product of two unrelated lists.
Definition: a multivalued dependency X ->> Y holds when, for a given X, the set of Y values is independent of the other columns. A relation is in 4NF when every non-trivial MVD has a superkey on the left. A join dependency says the relation equals the natural join of its projections; 5NF (project-join normal form) requires every join dependency to be implied by candidate keys.
employee_skills_languages(employee, skill, language) -- 2 skills x 3 languages = 6 rows per employee
employee ->> skill employee ->> language -- independent MVDs: violates 4NF
Split: employee_skills(employee, skill) employee_languages(employee, language)Real scenario (5NF): supplier_part_project(supplier, part, project) where the rule is "if a supplier supplies a part, and a project uses the part, and the supplier works with the project, then the supplier supplies that part to that project": the table decomposes losslessly into three binary tables and adds no information.
What prevents it: modelling each independent relationship as its own table (join tables).
Fix: two join tables; rejoin with a plain JOIN when you need the product.
Normal forms: what stays unsolved Good to know
Normal forms say nothing about types (is qty an integer?), ranges (qty > 0), cross-row rules (no overlapping bookings) or performance. Those are constraints and measurements, the next sections. Also outside normalization are DKNF (domain-key normal form, a theoretical ideal) and 6NF (temporal decomposition, used in anchor modelling and some data warehouses); you can ship software without either.
Denormalization
Normalize by default, then copy data deliberately where a measured read cost justifies it. Denormalization is not the absence of design; it is a second, derived representation with one source of truth and one refresh mechanism.
When denormalization is right Must-know
In plain words: you trade write complexity for read speed, on purpose, for a read path you have measured.
Common misunderstanding: "Denormalize to be safe for the future." Without a measured problem you only buy anomalies. Start from a slow query plan (Query Planning), not from a feeling.
Definition: denormalization stores a value that could be derived (a count, a sum, a joined name, a document) alongside its source. It is legitimate in four cases: an aggregate read far more often than written; a snapshot that must not change (the shipping address and unit price as they were at purchase are facts, not duplicates); a read model for a different access pattern (search, reporting); and a join that crosses a service or shard boundary.
Real scenarios: posts.comments_count on a feed of 50 posts; orders.total printed on every invoice; order_lines.unit_price copied from products.price at checkout; a nightly sales summary.
Strategies compared Must-know
| Strategy | How it stays correct | Staleness | Write cost | Failure mode |
|---|---|---|---|---|
Materialized view (PostgreSQL CREATE MATERIALIZED VIEW, Oracle MV, SQL Server indexed view) | REFRESH MATERIALIZED VIEW [CONCURRENTLY] on a schedule or after a batch | Until the next refresh | None per write; full or incremental rebuild | Stale reads; refresh locks the view unless CONCURRENTLY (needs a unique index) |
| Counter cache (column incremented in the write transaction) | Atomic UPDATE ... SET n = n + 1 in the same transaction as the insert | None if in the same transaction | One extra row update, hot-row contention | Drift if a code path forgets; lock contention on popular parents |
| Trigger | The database fires it for every writer | None | Per-row trigger overhead, hidden logic | Surprise at bulk loads; debugging is harder; MySQL triggers do not fire for cascaded FK actions |
Generated column (GENERATED ALWAYS AS (...) STORED) | Computed from the same row | None | Computed at write (stored) or read (virtual) | Only same-row expressions; no cross-row aggregates |
| Application-level copy (service code or event handler) | A code path writes both | Depends on the path | Code + discipline | The easiest to forget; needs a reconciliation query |
| Summary / rollup table (hourly, daily) | Batch job or stream aggregation | Until the next run | Batch cost off the hot path | Late-arriving data; backfills |
| Read model / search index (Elasticsearch, a CQRS projection) | Rebuilt from the source via events or CDC | Seconds to minutes | Separate pipeline | Rebuild time, schema drift |
Embedded document (MongoDB subdocument, jsonb copy) | Written together | None while in one document | Larger writes | Unbounded growth, update-in-many-places |
Materialized view Important
In plain words: a saved query result stored like a table that you refresh when you choose.
Common misunderstanding: "A materialized view updates itself like a view." A plain view is a stored query; a materialized view stores its result and is stale until refreshed. PostgreSQL has no automatic incremental maintenance (extensions and engines such as Materialize and SQL Server indexed views do).
Definition: CREATE MATERIALIZED VIEW name AS query, then REFRESH MATERIALIZED VIEW [CONCURRENTLY] name. CONCURRENTLY requires a unique index on the view and lets readers continue during the refresh.
Session 1 (cron refresh) Session 2 (dashboard)
1 REFRESH MATERIALIZED VIEW customer_totals;
2 SELECT * FROM customer_totals; -- blocks (ACCESS EXCLUSIVE)
3 -- done, 40 s later
4 -- rows arrive
fix: REFRESH MATERIALIZED VIEW CONCURRENTLY customer_totals; -- readers keep reading the old copyReal scenario: a top-customers leaderboard rebuilt every five minutes; a month-end revenue table.
CREATE MATERIALIZED VIEW customer_totals AS
SELECT o.customer_id, count(DISTINCT o.id) AS orders, sum(l.qty * l.unit_price_cents) AS spent_cents
FROM orders o JOIN order_lines l ON l.order_id = o.id
GROUP BY o.customer_id;
CREATE UNIQUE INDEX ON customer_totals (customer_id); -- required for CONCURRENTLY
REFRESH MATERIALIZED VIEW CONCURRENTLY customer_totals;Counter cache Must-know
In plain words: a column that stores "how many" or "how much", updated in the same transaction as the rows it counts.
Common misunderstanding: "Read the count, add one, write it back." Two concurrent writers both read 41 and both write 42: a lost update (Isolation Levels). Always increment in SQL: SET n = n + 1.
Definition: a denormalized aggregate column on the parent, maintained atomically with the child writes.
Request A (new order) Request B (new order, same customer)
1 BEGIN; BEGIN;
2 INSERT INTO orders ...; INSERT INTO orders ...;
3 UPDATE customer_stats SET order_count =
order_count + 1 WHERE customer_id = 7; -- row lock taken
4 UPDATE customer_stats SET order_count =
order_count + 1 WHERE customer_id = 7; -- waits
5 COMMIT; -- proceeds, sees 42, writes 43Real scenarios: comments_count, likes_count, wallet balance next to a ledger, stock next to stock movements.
Cost / limit: the parent row becomes a hot spot (every order of a very popular customer serializes on it). Fix with sharded counters (N rows per parent, summed on read) or by batching increments through a queue.
Go (inside the transaction that inserts the order) and Laravel:
// Package main keeps a denormalized counter honest inside the same transaction.
package main
import (
"context"
"database/sql"
"fmt"
)
// Line is one order line; money is integer minor units.
type Line struct {
ProductID string
Qty int
PriceCent int64
}
// PlaceOrder writes the order, its lines and the counter-cache row atomically.
// If any statement fails the whole transaction rolls back, so the copy cannot drift.
func PlaceOrder(ctx context.Context, db *sql.DB, customerID int64, lines []Line) (orderID int64, err error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer func() {
if err != nil {
_ = tx.Rollback()
}
}()
if err = tx.QueryRowContext(ctx,
`INSERT INTO orders (customer_id) VALUES ($1) RETURNING id`, customerID).Scan(&orderID); err != nil {
return 0, err
}
var total int64
for _, l := range lines {
if _, err = tx.ExecContext(ctx,
`INSERT INTO order_lines (order_id, product_id, qty, unit_price_cents) VALUES ($1, $2, $3, $4)`,
orderID, l.ProductID, l.Qty, l.PriceCent); err != nil {
return 0, err
}
total += int64(l.Qty) * l.PriceCent
}
// Atomic increment: no read-modify-write, so two concurrent orders cannot lose an update.
if _, err = tx.ExecContext(ctx,
`INSERT INTO customer_stats (customer_id, order_count, spent_cents)
VALUES ($1, 1, $2)
ON CONFLICT (customer_id) DO UPDATE
SET order_count = customer_stats.order_count + 1,
spent_cents = customer_stats.spent_cents + EXCLUDED.spent_cents`,
customerID, total); err != nil {
return 0, err
}
return orderID, tx.Commit()
}
// Drift lists customers whose cached numbers disagree with the source of truth.
const Drift = `
SELECT s.customer_id
FROM customer_stats s
JOIN (SELECT o.customer_id, count(DISTINCT o.id) AS n, sum(l.qty * l.unit_price_cents) AS spent
FROM orders o JOIN order_lines l ON l.order_id = o.id GROUP BY o.customer_id) x
ON x.customer_id = s.customer_id
WHERE s.order_count <> x.n
OR s.spent_cents <> x.spent`
func main() {
fmt.Println(len(Drift) > 0)
}// Inside DB::transaction(): an atomic increment, never read-modify-write.
DB::table('customers')->where('id', $customerId)->incrementEach([
'orders_count' => 1,
'spent_cents' => $cents,
]);Trigger-maintained copy Important
In plain words: the database itself updates the copy whenever the source changes, whoever wrote it.
Common misunderstanding: "Triggers are bad." They are hidden logic, which is the cost; the benefit is that every writer (a migration, a cron script, another service) is covered. Use them for invariants that must hold for every writer; avoid them for business workflows.
Definition: a trigger function runs BEFORE/AFTER INSERT/UPDATE/DELETE, per row or per statement. A BEFORE row trigger can change the row; an AFTER trigger sees the final state.
Real scenario: the lab's lines_ai trigger keeps customer_stats.spent_cents right for a bulk INSERT ... SELECT that application code would never see.
CREATE FUNCTION bump_stats() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO customer_stats (customer_id, order_count, spent_cents)
SELECT o.customer_id, 0, NEW.qty * NEW.unit_price_cents FROM orders o WHERE o.id = NEW.order_id
ON CONFLICT (customer_id) DO UPDATE
SET spent_cents = customer_stats.spent_cents + EXCLUDED.spent_cents;
RETURN NEW;
END $$;
CREATE TRIGGER order_lines_stats AFTER INSERT ON order_lines
FOR EACH ROW EXECUTE FUNCTION bump_stats();Remember UPDATE and DELETE of lines too, and TRUNCATE: a counter trigger that handles only inserts drifts the first time a line is edited. This is why a drift query is part of the design.
Snapshot columns Important
In plain words: copy a value at the moment it matters and never update the copy.
Common misunderstanding: "Storing unit_price on the order line duplicates products.price." It is a different fact: the price charged, which must survive a later price change.
Definition: a column that records a fact as of a time (price at purchase, address at shipment, tax rate applied). It is not a derived duplicate because the source is allowed to change.
Real scenario: invoices must re-print identically years later; a refund is computed from what the customer paid, not today's price.
The drift query Must-know
Every denormalized copy gets a query that recomputes it from the source and returns the rows that disagree. Schedule it, alert when it is not empty, and make the fix a one-liner.
SELECT s.customer_id, s.order_count, x.n, s.spent_cents, x.spent
FROM customer_stats s
JOIN (SELECT o.customer_id, count(DISTINCT o.id) AS n, sum(l.qty * l.unit_price_cents) AS spent
FROM orders o JOIN order_lines l ON l.order_id = o.id GROUP BY o.customer_id) x
ON x.customer_id = s.customer_id
WHERE s.order_count <> x.n OR s.spent_cents <> x.spent; -- expect zero rowsKeys
Surrogate vs natural keys Must-know
In plain words: a natural key is a value the business already uses to identify a thing (email, ISO country code, invoice number). A surrogate key is an invented one (id = 42) that means nothing.
Common misunderstanding: "An email is unique, so it should be the primary key." Emails change, are reused, are case-insensitive in practice, and are copied into every referencing table. Use a surrogate PK and keep the natural key as a UNIQUE constraint.
Definition: a surrogate key is system-generated, immutable and meaningless; a natural key carries meaning and changes when the world does.
Session 1 Session 2
1 -- users PK = email; 12 tables reference it
2 UPDATE users SET email = 'new@x.com'
WHERE email = 'old@x.com'; -- 12 tables need ON UPDATE CASCADE, or it fails
3 -- with surrogate id: UPDATE users SET email = ... WHERE id = 7; -- one rowReal scenarios: a user changes email; a country code is re-assigned (it happens); an invoice numbering scheme changes after an acquisition; two tenants use the same SKU.
Rules: use a natural key as PK only for stable reference data you control (a countries table keyed by ISO 3166-1 alpha-2, a currencies table by ISO 4217). Everywhere else: surrogate PK plus UNIQUE on the natural key.
Choosing the surrogate: identity vs UUID vs ULID Must-know
In plain words: the question is where the ID is made (in the database or outside it) and what it does to the index.
Common misunderstanding: "UUIDs are slow, so bigint is always better." The cost of a random UUIDv4 is index locality, not size alone: every insert lands at a random leaf page, causing page splits and cache misses, and (on PostgreSQL) full-page writes after each checkpoint. Time-ordered UUIDv7 and ULID recover most of the locality. See B-Tree vs B+Tree and ID Generation at Scale.
Definition:
| Type | How it is made | Order | Size | Notes |
|---|---|---|---|---|
bigint GENERATED ALWAYS AS IDENTITY | A sequence in the database | Monotonic per sequence | 8 bytes | Gaps after rollbacks; the sequence is a single point of allocation; guessable |
serial / bigserial | Sequence plus default | Same | 4 / 8 bytes | The wiki says use identity columns for new applications |
UUIDv4 (gen_random_uuid() or uuidv4()) | 122 random bits | None | 16 bytes | Unguessable, generated anywhere, scattered inserts |
UUIDv7 (uuidv7() in the current PostgreSQL manual; Laravel HasUuids generates it) | 48-bit Unix millisecond timestamp plus random bits | Time-ordered | 16 bytes | Locality close to bigint, global uniqueness; leaks creation time |
| ULID | 48-bit timestamp plus 80 random bits, Crockford base32 | Time-ordered | 26 characters (or 16 bytes as binary) | Sortable and URL-friendly; Laravel HasUlids, $table->ulid() |
| Snowflake-style 64-bit | Timestamp + machine id + sequence | Time-ordered | 8 bytes | Needs worker-id allocation; fits in bigint |
Real scenarios: an order table with millions of rows per day where inserts must be cheap (bigint or UUIDv7); an offline-first mobile app that creates records before syncing (UUIDv7, generated on the client); a public URL such as /invoices/01HV... that must not reveal how many invoices exist (a public UUID/ULID beside an internal bigint key).
| Engine | Notes |
|---|---|
| PostgreSQL | Heap tables: the PK is just another B-tree, so a random UUID costs index locality and WAL, not table layout |
| MySQL InnoDB | The table is the primary-key B+tree, and every secondary index carries the PK: a random UUID PK scatters the table itself and bloats every index |
| SQL Server | uniqueidentifier with NEWSEQUENTIALID() for ordered values; clustered index on a random GUID fragments |
| Oracle | Sequences and identity columns (12c+); RAW(16) for UUIDs |
| SQLite | INTEGER PRIMARY KEY is the rowid alias and is the fastest key |
| CockroachDB | Sequential keys create a hot range; random UUIDs or hash-sharded indexes spread writes |
| MongoDB | ObjectId is time-prefixed, 12 bytes |
| Redis | No table; key naming is the schema |
-- Internal key small and sequential, public id opaque and stable.
CREATE TABLE invoices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
public_id uuid NOT NULL DEFAULT uuidv7() UNIQUE, -- or gen_random_uuid() on older servers
number text NOT NULL UNIQUE -- the natural key, kept as a constraint
);// Migration and model for a ULID key (Laravel 13 docs: HasUlids, $table->ulid()).
Schema::create('articles', function (Blueprint $table) {
$table->ulid('id')->primary();
$table->timestampsTz();
});
class Article extends Model
{
use HasUlids; // Article::create([...])->id is a 26-character ULID
}Identity details: GENERATED ALWAYS rejects explicit values unless you write OVERRIDING SYSTEM VALUE; GENERATED BY DEFAULT accepts them (useful for imports, risky for collisions). Sequences are not transactional: a rolled-back insert burns a number, so gaps are normal and a gapless invoice series needs its own allocation table. After a bulk import with explicit ids, reset with SELECT setval(pg_get_serial_sequence('t','id'), max(id)) FROM t;.
Composite keys Important
In plain words: a key made of two or more columns, such as (order_id, product_id).
Common misunderstanding: "Always add a surrogate id to a join table." A composite primary key is correct, smaller and enforces the rule that a product appears once per order; add a surrogate only if other tables must reference the line itself, or your ORM insists.
Definition: a PRIMARY KEY or UNIQUE constraint over several columns. The B-tree is ordered by the first column, then the second, so column order decides which queries it can serve (the left-prefix rule, see Indexing).
Real scenarios: order_lines(order_id, product_id); memberships(user_id, group_id); per-tenant uniqueness UNIQUE (tenant_id, slug); a child that references a composite parent needs a composite foreign key.
CREATE TABLE memberships (
user_id bigint NOT NULL REFERENCES users (id) ON DELETE CASCADE,
group_id bigint NOT NULL REFERENCES groups (id) ON DELETE CASCADE,
role text NOT NULL DEFAULT 'member',
PRIMARY KEY (user_id, group_id) -- also the index for "groups of a user"
);
CREATE INDEX ON memberships (group_id, user_id); -- the reverse lookupLaravel builds the same with $table->primary(['user_id', 'group_id']); Eloquent does not support composite primary keys on models natively, so a pivot-style table is used through belongsToMany rather than as a model.
Constraints
A constraint is a rule the database enforces on every write, under concurrency, against every client. PostgreSQL's manual lists the kinds: check, not-null, unique, primary key, foreign key and exclusion constraints.
Foreign keys and referential actions Must-know
In plain words: a foreign key says "this column must match a row in that table", and the referential action says what to do when the parent goes away.
Common misunderstanding: "Foreign keys slow everything down, so skip them." They cost an index lookup per child write and a lock on the parent row (FOR KEY SHARE); what they buy is that orphan rows are impossible. The classic mistake is the opposite one: forgetting to index the child column, so deleting a parent scans the whole child table.
Definition: REFERENCES parent (key) ON DELETE action ON UPDATE action. Actions: NO ACTION (default), RESTRICT, CASCADE, SET NULL, SET DEFAULT.
Session 1 Session 2
1 BEGIN;
2 DELETE FROM customers WHERE id = 7; -- customer has 2 orders, ON DELETE RESTRICT
3 -- ERROR 23503: update or delete on table "customers" violates foreign key constraint
4 INSERT INTO orders (customer_id, ...) VALUES (999, ...);
5 -- ERROR 23503: insert or update on table "orders" violates foreign key constraintReal scenarios: order lines that must die with their order (CASCADE); an invoice that must block deletion of its customer (RESTRICT); an optional assigned_to that clears when the user leaves (SET NULL); a default "unknown" category (SET DEFAULT).
| Action | PostgreSQL | MySQL InnoDB | SQL Server | Oracle | SQLite |
|---|---|---|---|---|---|
NO ACTION (default) | Error at end of statement; checkable at commit when deferrable | Same as RESTRICT | Default; error at end of statement | Default (error) | Default; deferrable |
RESTRICT | Error immediately, never deferred | Supported | Not available (use NO ACTION) | Not available | Supported |
CASCADE | Supported | Supported (cascades do not fire triggers) | Supported; "multiple cascade paths" restriction | ON DELETE CASCADE only (no ON UPDATE) | Supported |
SET NULL | Supported | Supported (column must be nullable) | Supported | ON DELETE SET NULL | Supported |
SET DEFAULT | Supported | Parsed but rejected by InnoDB | Supported | Not available | Supported |
(The MySQL, SQL Server and Oracle cells are from my knowledge of those products; the MySQL manual returned HTTP 403 to automated fetching, so they were not re-read for this page. SQLite enforces foreign keys only after PRAGMA foreign_keys = ON, per connection.)
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers (id) ON DELETE RESTRICT ON UPDATE CASCADE,
assigned_to bigint REFERENCES staff (id) ON DELETE SET NULL
);
CREATE INDEX orders_customer_id_idx ON orders (customer_id); -- PostgreSQL does NOT index the child column for you// Map the constraint error to a domain error (pgx).
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23503" { // foreign_key_violation
return ErrCustomerHasOrders
}// Laravel migration helpers (Laravel 13 docs): cascadeOnDelete, restrictOnDelete, nullOnDelete, noActionOnDelete.
$table->foreignId('customer_id')->constrained()->restrictOnDelete()->cascadeOnUpdate();
$table->foreignId('assigned_to')->nullable()->constrained('staff')->nullOnDelete();Deferrable constraints Important
In plain words: normally a foreign key is checked after each statement. A deferrable one is checked only at COMMIT, so you can insert child and parent in any order or swap two unique values.
Common misunderstanding: "DEFERRABLE makes the constraint optional." The rule is still enforced, just at the end of the transaction; if it is broken at commit, the whole transaction fails, which makes the error appear far from the statement that caused it.
Definition: a constraint is NOT DEFERRABLE (default), DEFERRABLE INITIALLY IMMEDIATE or DEFERRABLE INITIALLY DEFERRED. SET CONSTRAINTS name | ALL DEFERRED | IMMEDIATE switches the mode inside a transaction. In PostgreSQL only UNIQUE, PRIMARY KEY, REFERENCES and EXCLUDE constraints are affected; NOT NULL and CHECK are always immediate. A non-deferrable unique constraint is checked row by row, so UPDATE t SET pos = pos + 1 can fail midway.
Session 1
1 BEGIN;
2 SET CONSTRAINTS orders_customer_fk DEFERRED;
3 INSERT INTO orders (id, customer_id) VALUES (1, 7); -- customer 7 does not exist yet: allowed
4 INSERT INTO customers (id, name) VALUES (7, 'Ada');
5 COMMIT; -- check runs here: passes
-- had customer 7 never been inserted: ERROR 23503 at COMMITReal scenarios: loading two tables with a circular reference; reordering a list with UNIQUE (list_id, position); bulk import where parent and child arrive out of order; swapping two values.
| Engine | Deferrable constraints |
|---|---|
| PostgreSQL | Yes: DEFERRABLE INITIALLY DEFERRED on UNIQUE, PK, FK, EXCLUDE |
| Oracle | Yes: DEFERRABLE INITIALLY DEFERRED |
| SQLite | Foreign keys only (DEFERRABLE INITIALLY DEFERRED; also PRAGMA defer_foreign_keys) |
| MySQL InnoDB | No: checks are immediate (SET foreign_key_checks = 0 disables them, which is a bulk-load tool, not a design) |
| SQL Server | No deferral |
| CockroachDB | Not supported for FKs at the time of writing; verify in its docs |
CREATE TABLE list_items (
list_id bigint NOT NULL,
position integer NOT NULL,
UNIQUE (list_id, position) DEFERRABLE INITIALLY DEFERRED
);
BEGIN;
UPDATE list_items SET position = position + 1 WHERE list_id = 1; -- passes: checked at COMMIT
COMMIT;CHECK constraints Must-know
In plain words: a rule about one row, such as price >= 0 or ends_at > starts_at.
Common misunderstanding: "A CHECK can look at other rows or tables." PostgreSQL does not support CHECK constraints that reference other rows or tables: the manual says such a check may appear to work but cannot guarantee the database never reaches a state where the condition is false, and a dump and restore can fail. Use UNIQUE, EXCLUDE or FOREIGN KEY for cross-row rules.
Definition: CHECK (expression) evaluated for each inserted or updated row; the row is rejected if the expression is FALSE. If it is NULL (unknown), the row is accepted.
Session 1
1 CREATE TABLE products (price numeric CHECK (price >= 0));
2 INSERT INTO products VALUES (-1); -- ERROR 23514 check_violation
3 INSERT INTO products VALUES (NULL); -- accepted: NULL >= 0 is unknown, not false
4 -- fix: price numeric NOT NULL CHECK (price >= 0)Real scenarios: status IN (...); char_length(slug) BETWEEN 3 AND 63; (a IS NULL) <> (b IS NULL) (exactly one of two); num_nonnulls(post_id, video_id) = 1 for the FK-per-target polymorphic alternative.
| Engine | CHECK |
|---|---|
| PostgreSQL | Enforced; NOT VALID then VALIDATE CONSTRAINT for large tables (Schema Migrations) |
| MySQL | Enforced in 8.0 (5.7 and earlier parsed and ignored it); error 3819 |
| SQL Server, Oracle | Enforced; Oracle ENABLE NOVALIDATE |
| SQLite | Enforced |
| MongoDB | $jsonSchema validators with validationAction: error |
EXCLUDE constraints Important
In plain words: "no two rows may overlap", the generalization of UNIQUE from equality to any operator.
Common misunderstanding: "Overlap checks belong in application code, with a SELECT first." Two requests both see no conflict and both insert (check-then-insert, a write-skew race). Only a constraint is atomic. The booking solution at Serializable is in Isolation Levels; the schema-level form is below.
Definition: EXCLUDE USING gist (col WITH operator, ...) guarantees that no two rows compare true on all the listed operators. It needs an index method that supports the operators (GiST or SP-GiST; btree_gist provides = on scalar types for mixed constraints). Violation is SQLSTATE 23P01 (exclusion_violation). PostgreSQL-only: MySQL, SQL Server, Oracle and SQLite have no equivalent.
Session 1 Session 2
1 BEGIN; BEGIN;
2 INSERT INTO bookings (room_id, during)
VALUES (1, '[10:00,11:00)');
3 INSERT INTO bookings (room_id, during)
VALUES (1, '[10:30,11:30)'); -- waits for Session 1
4 COMMIT;
5 -- ERROR 23P01 conflicting key value violates exclusion constraintCREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE bookings (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
room_id bigint NOT NULL,
during tstzrange NOT NULL,
EXCLUDE USING gist (room_id WITH =, during WITH &&)
);UNIQUE, partial unique indexes and NULLS NOT DISTINCT Important
In plain words: UNIQUE forbids duplicates, but two NULLs are not "equal", so they do not count as duplicates.
Common misunderstanding: "UNIQUE (email) allows only one row with a missing email." By default it allows any number: PostgreSQL's manual says two null values are not considered equal and the behaviour can be changed with NULLS NOT DISTINCT. Which products differ: SQL Server treats NULL as a value in a unique index (only one), PostgreSQL by default does not.
Definition: UNIQUE, UNIQUE NULLS NOT DISTINCT (documented in the current PostgreSQL manual; I did not check which release added it), and a partial unique index CREATE UNIQUE INDEX ... WHERE condition for "unique among live rows" (soft deletes) or "one active subscription per user".
CREATE UNIQUE INDEX users_email_live ON users (lower(email)) WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX one_active_sub ON subscriptions (user_id) WHERE status = 'active';NOT NULL and three-valued logic Must-know
In plain words: NULL does not mean zero or empty; it means unknown, and SQL has three truth values: true, false and unknown.
Common misunderstanding: "WHERE x <> 1 returns every row where x is not 1." It silently drops rows where x IS NULL, because NULL <> 1 is unknown and WHERE keeps only TRUE.
Definition: any comparison with NULL yields unknown; NOT unknown is unknown; unknown AND false is false; unknown OR true is true. IS NULL, IS DISTINCT FROM, COALESCE, NULLIF and NOT EXISTS are the tools.
Query Result
1 SELECT NULL = NULL; NULL -- not true
2 SELECT 1 WHERE NULL IN (1, NULL); (0 rows)
3 SELECT * FROM t WHERE x <> 1; skips rows with x IS NULL
4 SELECT * FROM t WHERE x IS DISTINCT FROM 1; includes them
5 SELECT * FROM a WHERE id NOT IN (SELECT a_id FROM b); -- returns 0 rows if any b.a_id is NULL
6 SELECT * FROM a WHERE NOT EXISTS (SELECT 1 FROM b WHERE b.a_id = a.id); -- correctReal scenarios: an anti-join that silently returns nothing after one bad import row; an AVG(rating) that ignores NULL ratings while COUNT(*) counts them; COUNT(col) vs COUNT(*); a LEFT JOIN filtered in WHERE that became an inner join.
| Engine | NULL behaviours worth knowing |
|---|---|
| PostgreSQL | NULL in UNIQUE is distinct by default; NOT IN with a NULL returns no rows |
| MySQL | Same three-valued logic; unique index allows many NULLs |
| SQL Server | Unique index allows one NULL |
| Oracle | Empty string '' is NULL (a classic migration trap); composite unique indexes ignore rows that are all NULL |
| SQLite | NULLs distinct in UNIQUE; typing is flexible |
Design rules: make a column NOT NULL unless absence is a real state; prefer a separate table over many mostly-null columns; give a flag a default; NULL for "not yet known" and a sentinel ('', 0, -1, 9999-12-31) only when you accept the bugs it causes.
Domains Good to know
In plain words: a named, reusable type with built-in rules, such as email_address or percent.
Common misunderstanding: "A domain is a new storage type." It is a base type plus constraints and a default; changing the constraint later revalidates every column that uses it.
Definition: CREATE DOMAIN name AS data_type [DEFAULT ...] [NOT NULL] [CHECK ...].
CREATE DOMAIN percent AS numeric(5,2) CHECK (VALUE BETWEEN 0 AND 100);
CREATE DOMAIN email AS text CHECK (VALUE ~ '^[^@\s]+@[^@\s]+$');
CREATE TABLE discounts (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, rate percent NOT NULL);MySQL, SQL Server and SQLite have no CREATE DOMAIN; SQL Server has alias types, Oracle has CREATE DOMAIN from 23ai.
Modelling patterns
Enums vs lookup tables Must-know
In plain words: a column that can hold one of a few named values can be a native ENUM, a text column with a CHECK, or a foreign key to a small lookup table.
Common misunderstanding: "An ENUM is always the cleanest." A PostgreSQL ENUM is compact, but every change to its value list is DDL (adding a value is cheap; removing or reordering is not supported), and you cannot attach attributes (label, colour, sort order, is_active) to a value. That is the maintainer's judgement, not a quoted rule.
Definition: CREATE TYPE status AS ENUM (...) (PostgreSQL), ENUM('a','b') column type (MySQL), CHECK (status IN (...)), or status_id referencing statuses(id).
Session 1 Session 2
1 -- new business state "refunded"
2 -- ENUM: ALTER TYPE order_status ADD VALUE 'refunded'; -- DDL, deploy-coupled
3 -- CHECK: ALTER TABLE orders DROP CONSTRAINT ...; ADD CONSTRAINT ... CHECK (... 'refunded');
4 -- lookup: INSERT INTO order_statuses VALUES ('refunded', 'Refunded', 60); -- data, no DDL| Option | Adding a value | Extra attributes | Typical engine support |
|---|---|---|---|
Native ENUM | DDL (ALTER TYPE ... ADD VALUE); MySQL ALTER TABLE rewrites the column definition | No | PostgreSQL, MySQL (stores a 1-2 byte index, sorts by definition order) |
text + CHECK | Replace the constraint | No | Everywhere |
| Lookup table + FK | INSERT | Yes (label, sort, active) | Everywhere |
Real scenarios: order status (stable, small: text + CHECK or ENUM); country, currency, role (changes, has attributes: lookup table); a status that has a UI label in six languages (lookup table, translations beside it).
MySQL note: ENUM values are stored as an index and compare by definition order; an invalid value inserts '' in non-strict mode, which is one more reason to run STRICT_TRANS_TABLES. Reordering is a table alteration.
Laravel: $table->enum('status', OrderStatus::cases()) creates the DB-level enum or check on engines that support it; the cast 'status' => OrderStatus::class maps it to a PHP backed enum in the model.
Polymorphic associations Important
In plain words: one comments table that can belong to a post, a video or a photo, using two columns: commentable_type and commentable_id.
Common misunderstanding: "It is just a foreign key with a type tag." The database cannot enforce it: commentable_id points to some table the engine does not know about, so there is no foreign key, no ON DELETE, no referential integrity, and orphans accumulate.
Definition: a relationship whose target table is chosen per row by a type column. Laravel creates it with $table->morphs('commentable'), and morphTo() on the model resolves it. Rails calls the same pattern polymorphic: true.
Session 1 Session 2
1 INSERT INTO comments (commentable_type, commentable_id, body)
VALUES ('post', 42, 'hi');
2 DELETE FROM posts WHERE id = 42; -- succeeds: no FK
3 SELECT * FROM comments WHERE commentable_type = 'post' AND commentable_id = 42; -- 1 orphan rowReal scenarios: comments, tags, attachments, activity logs, notifications. Problems in production: orphan rows after deletes, a stored class name that breaks after a refactor (App\Models\Post becomes App\Domain\Post), no join from the database side, and an index that must be (commentable_type, commentable_id).
| Alternative | How | Pro | Con |
|---|---|---|---|
| Polymorphic columns | type + id | One table, easy to extend | No FK; orphans; stringly-typed |
One FK per target + CHECK num_nonnulls(...) = 1 | post_id, video_id nullable | Real FKs, ON DELETE CASCADE | Wider table, a column per new target |
| Join table per target | post_comments(post_id, comment_id) | Normalized, FKs | More tables and joins |
| Supertype table | commentables(id) that posts and videos extend | One FK target | Extra row per entity |
Mitigations when you keep polymorphism: store stable short names with Relation::enforceMorphMap, add a periodic orphan-detection query, and delete children in the application or a trigger when the parent goes. See the Laravel snippet:
<?php
// app/Models/Comment.php: a polymorphic association and the guard rails it needs.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\Relation;
// app/Providers/AppServiceProvider.php, boot(): store short stable names, not class names.
// Relation::enforceMorphMap(['post' => Post::class, 'video' => Video::class]);
class Comment extends Model
{
// comments.commentable_type + comments.commentable_id (created by $table->morphs('commentable')).
// The database CANNOT put a foreign key on commentable_id: it does not know which table it points to.
public function commentable(): MorphTo
{
return $this->morphTo();
}
}
// The FK-friendly alternative: one nullable FK per target plus a CHECK that exactly one is set.
// post_id bigint REFERENCES posts (id) ON DELETE CASCADE,
// video_id bigint REFERENCES videos (id) ON DELETE CASCADE,
// CHECK (num_nonnulls(post_id, video_id) = 1)
class Post extends Model
{
}
class Video extends Model
{
}EAV: entity-attribute-value Important
In plain words: instead of columns, one table of (entity_id, attribute, value) rows, so any entity can have any attribute without a migration.
Common misunderstanding: "EAV gives me a flexible schema for free." It gives up types (every value is text), NOT NULL, CHECK, foreign keys and efficient queries, and needs one join (or FILTER) per attribute to rebuild a row.
Definition: the anti-pattern of storing attribute names as data. A query for "red shoes under 50" becomes a self-join per attribute.
products_eav the same product as one row
entity | attribute | value id | colour | size | price
1 | colour | red 1 | red | 42 | 49.90
1 | size | 42
1 | price | 49.90 -- price is text: '49.90' < '5.00' sorts wrongReal scenarios: product catalogues with thousands of attributes per category (the genuine use case); medical records (the original EAV domain); user custom fields in SaaS.
Fix: model the stable core as columns; put the long tail in one jsonb column with a GIN index; or keep EAV only for the truly open-ended part and cast on read. A document database (MongoDB) or a search index handles sparse attributes better than an EAV table does.
JSONB: when and when not Must-know
In plain words: jsonb stores a JSON document inside a column in a binary form PostgreSQL can index and query.
Common misunderstanding: "jsonb means no schema." It means the schema lives in application code, unchecked. The PostgreSQL manual recommends jsonb over json for most applications; json keeps an exact copy of the text (whitespace, key order, duplicate keys), jsonb does not preserve whitespace, key order or duplicate keys, but supports indexing and is faster to process.
Definition: operators -> (get as json), ->> (get as text), @> (contains), ? (key exists), #> (path), plus jsonpath. GIN indexes: the default jsonb_ops supports ?, ?|, ?&, @>, @?, @@; the non-default jsonb_path_ops supports only @>, @?, @@ but is smaller and faster.
Query Notes
1 SELECT meta->>'gift_message' FROM orders WHERE id=1; text, NULL if the key is absent
2 SELECT * FROM orders WHERE meta @> '{"gift": true}'; uses a GIN index
3 SELECT * FROM orders WHERE (meta->>'qty')::int > 3; cast on every row: no index, wrong for bad data
4 -- a key queried in 3 of every 4 queries: that is a columnUse jsonb for | Use columns for |
|---|---|
| Sparse, optional, per-tenant extras; third-party payloads kept as received | Anything you filter, join, sort, aggregate or constrain on in most queries |
| Data whose shape you do not own (webhook bodies, feature flags) | Money, dates, foreign keys, anything needing a type |
| Schemaless documents read and written whole | Anything needing NOT NULL or UNIQUE |
Audit snapshots (old/new) | Fields shown in every list view |
Real scenarios: a webhook payload stored verbatim; a per-tenant settings blob; an attributes column for the long tail of an EAV-like catalogue; a JSON audit diff.
Pitfalls: jsonb rejects numbers outside numeric range and keeps trailing fractional zeros, which matters when a JavaScript client sends large integers; updating one key rewrites the whole document (TOAST for large values); there is no per-key statistics, so the planner guesses selectivity badly.
| Engine | JSON |
|---|---|
| PostgreSQL | json, jsonb, GIN indexes, jsonpath |
| MySQL | One JSON type (binary); index through generated columns or functional indexes; no jsonb name |
| SQL Server | nvarchar with JSON_VALUE/OPENJSON; a native json type is newer |
| Oracle | JSON type from 21c; earlier CLOB with IS JSON |
| SQLite | JSON functions over TEXT; the built-in jsonb format is separate |
| MongoDB | The native model (BSON) |
Constrain what you can: CHECK (jsonb_typeof(meta) = 'object').
Arrays Good to know
In plain words: PostgreSQL lets a column be an array, such as tags text[].
Common misunderstanding: "An array column is the same as a child table." You cannot put a foreign key on array elements, and updating one element rewrites the row; use arrays for small, value-like lists you never join on (tags, a list of allowed IP ranges), and child tables for anything with identity.
Definition: type[] with operators @>, <@, &&, = ANY(array); GIN indexes accelerate containment and overlap.
CREATE TABLE posts (id bigint PRIMARY KEY, tags text[] NOT NULL DEFAULT '{}');
CREATE INDEX posts_tags_gin ON posts USING gin (tags);
SELECT id FROM posts WHERE tags @> ARRAY['postgres']; -- uses the GIN index
SELECT id FROM posts WHERE 'sql' = ANY (tags); -- sequential unless an expression index fitsArray dimensions and declared sizes are not enforced by PostgreSQL. MySQL, SQL Server, Oracle and SQLite have no array column; they use JSON or child tables.
Range and multirange types Good to know
In plain words: one value that represents an interval, such as the dates a price was valid: [2026-01-01, 2026-02-01).
Common misunderstanding: "Two date columns do the same thing." They do, until you need to say "these must not overlap", which is one EXCLUDE constraint on a range and a pile of buggy code on two columns.
Definition: built-in range types int4range, int8range, numrange, tsrange, tstzrange, daterange; every range type has a multirange type (an ordered list of non-contiguous, non-empty, non-null ranges). Operators: && overlaps, @> contains, -|- adjacent. Discrete ranges are canonicalised to [).
Real scenarios: bookings, price validity, employment periods, IP allocations (inet/cidr plus &&-like operators), time-travel tables.
SELECT daterange('2026-01-01', '2026-02-01') @> DATE '2026-01-31'; -- true
SELECT tstzrange(now(), now() + interval '1 hour') && tstzrange(now() + interval '30 min', now() + interval '2 hours'); -- trueSoft deletes Important
In plain words: instead of deleting a row, set deleted_at and hide it.
Common misunderstanding: "Soft delete is a safer DELETE." It leaks: every query must remember WHERE deleted_at IS NULL; UNIQUE (email) now blocks re-registration; foreign keys still point at hidden rows; the table grows forever; and it is not a privacy-compliant deletion.
Definition: a nullable timestamp (or boolean) marks a row as deleted. Laravel's SoftDeletes trait adds the global scope and withTrashed()/onlyTrashed()/restore(); the migration helper is softDeletes() (nullable deleted_at).
Real scenarios: "undo delete" on documents; accounting rows you must retain; a customer closed account kept for the audit.
| Concern | Fix |
|---|---|
| Uniqueness | Partial unique index WHERE deleted_at IS NULL |
| Forgotten filter | A view over the live rows, or the ORM global scope; Row Level Security |
| Growth | Archive or purge job; partition by deleted_at or move to an archive table |
| Privacy deletion | Hard-delete or anonymize on schedule; a flag is not erasure |
| Alternative | An archived_at plus an append-only history table, or event sourcing |
Audit columns and history Important
In plain words: columns that say who and when: created_at, updated_at, created_by, deleted_at, version.
Common misunderstanding: "updated_at is an audit log." It records only the last change; the previous values are gone. Auditing needs an append-only history table written by a trigger or by the application in the same transaction (or pgaudit for statement-level logging; see Database Security).
Definition: created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz (set by a trigger or the ORM), created_by, updated_by, optionally a version integer for optimistic locking (Optimistic vs Pessimistic Locking). Eloquent maintains created_at/updated_at automatically; $table->timestampsTz() creates them as timestamptz.
Real scenarios: "who changed this price?"; regulators asking for the state of a record on a date; syncing changes by updated_at > :cursor.
Pitfall: a bulk UPDATE through the query builder does not touch updated_at in Eloquent; a trigger does.
CREATE TABLE price_history (
product_id bigint NOT NULL,
valid tstzrange NOT NULL,
price numeric(12,2) NOT NULL CHECK (price >= 0),
changed_by bigint NOT NULL,
EXCLUDE USING gist (product_id WITH =, valid WITH &&) -- no overlapping periods per product
);Multi-tenant columns Important
In plain words: in a shared-schema SaaS, every row carries tenant_id, and every query must filter by it.
Common misunderstanding: "A global UNIQUE (email) is fine." In a tenant-scoped table uniqueness is UNIQUE (tenant_id, email), and foreign keys should include the tenant (FOREIGN KEY (tenant_id, customer_id) REFERENCES customers (tenant_id, id)) so a row cannot reference another tenant's parent.
Definition: a leading tenant_id column in the key and the index, enforced with composite foreign keys and Row Level Security. Strategy choice (shared schema, schema per tenant, database per tenant) is in Multi-Tenancy Strategies; this page only fixes the columns.
Real scenario: invoices(tenant_id, id, ...) with PRIMARY KEY (tenant_id, id) so every tenant's data is physically clustered and partitionable by tenant.
Table partitioning hint Good to know
Design for partitioning early, even if you do not partition yet: partition keys must be part of every unique constraint and primary key on a partitioned PostgreSQL table, so a time-partitioned table has PRIMARY KEY (id, created_at), not PRIMARY KEY (id). Choose time (created_at) for append-mostly data and tenant or hash for isolation. The mechanics, pruning and operations are in Partitioning & Sharding in PostgreSQL; the billion-row playbook is in Billion-Row Tables.
Naming conventions Good to know
The wiki's reason for lowercase is mechanical: unquoted identifiers fold to lower case in PostgreSQL, so NamesLikeThis forces quoting forever.
| Rule | Example | Why |
|---|---|---|
snake_case, lowercase, no quotes | order_lines | Unquoted identifiers are case-folded |
| Plural table names (Eloquent default) | orders, customers | Laravel infers orders from Order |
<singular>_id foreign keys | customer_id | Eloquent infers customer_id for belongsTo(Customer) |
Booleans as is_/has_ | is_active | Reads as a question |
Timestamps as *_at, dates as *_on | paid_at, due_on | Type visible from the name |
| Name constraints and indexes | orders_customer_id_fkey | Error messages and migrations become readable |
| No reserved words, no abbreviations | order is reserved: use orders | Avoids quoting |
Data types
timestamptz vs timestamp and time zones Must-know
In plain words: timestamptz stores one exact moment in time; timestamp stores whatever calendar-and-clock reading you gave it, with no way to know where.
Common misunderstanding: "timestamptz stores the time zone." It does not. PostgreSQL's manual says the input zone is converted to UTC for storage and "The originally stated or assumed time zone is not retained"; on output the value is converted to the session TimeZone. The wiki: "Don't use the timestamp type to store timestamps, use timestamptz (also known as timestamp with time zone) instead."
Definition: timestamptz and timestamp are both 8 bytes with microsecond resolution. For timestamp, PostgreSQL "will silently ignore any time zone indication" in the input. AT TIME ZONE converts between them. the manual says the definition of timetz has properties that lead to "questionable usefulness"; the wiki says do not use it.
Session 1 (TimeZone = 'Asia/Tehran') Session 2 (TimeZone = 'UTC')
1 INSERT INTO t (a_tz, a_plain)
VALUES ('2026-03-01 10:00+03:30', '2026-03-01 10:00+03:30');
2 SELECT a_tz, a_plain FROM t;
-- 2026-03-01 10:00:00+03:30 | 2026-03-01 10:00:00 (+03:30 silently dropped from a_plain)
3 SELECT a_tz, a_plain FROM t;
4 -- 2026-03-01 06:30:00+00 | 2026-03-01 10:00:00 (same instant, same picture)Real scenarios: an event that happens at one instant for everyone (payment time: timestamptz); a future appointment "9:00 in Berlin" that must stay 9:00 after a DST rule change (store the local timestamp plus the zone name); a birthday (date, no zone).
Rules: store instants as timestamptz and pass UTC from the application; store the user's zone separately as an IANA name (Asia/Tehran), not an offset; for future local times store local time plus zone name, because the offset can change by law; set the session TimeZone explicitly rather than trusting the server default.
| Engine | Behaviour |
|---|---|
| PostgreSQL | timestamptz converts to UTC on write and to the session zone on read; timestamp stores the wall-clock reading |
| MySQL | TIMESTAMP converts to UTC and back using the session time_zone, range up to 2038-01-19; DATETIME stores what you give it, range to year 9999, no conversion |
| SQL Server | datetimeoffset keeps the offset (not the zone name); datetime2 has none |
| Oracle | TIMESTAMP WITH TIME ZONE keeps the offset or region; TIMESTAMP WITH LOCAL TIME ZONE normalizes; DATE includes a time of day |
| SQLite | No date type: stores TEXT (ISO-8601), REAL (Julian day) or INTEGER (Unix time) |
| MongoDB | Date is UTC milliseconds |
// Send UTC; the driver sends an instant, the zone is a display concern.
paidAt := time.Now().UTC()
_, err := db.ExecContext(ctx, `UPDATE orders SET paid_at = $1 WHERE id = $2`, paidAt, id)
// Reading back: scan into time.Time, then .In(userLocation) only for display.Laravel: $table->timestampTz('paid_at'), cast 'paid_at' => 'immutable_datetime', and keep config('app.timezone') as UTC.
Date and interval pitfalls Important
In plain words: dates are not numbers, months have different lengths, and some local days have 23 or 25 hours.
Common misunderstanding: "BETWEEN '2026-06-01' AND '2026-06-08' gives me the first week." On a timestamp column it includes exactly midnight of June 8 but nothing after it; the wiki: BETWEEN uses a closed-interval comparison, so both ends are included. Use >= start AND < end.
Definition: interval stores months, days and microseconds separately, so interval '1 month' is not a fixed number of days and interval '1 day' across a DST change is 23 or 25 hours when added to a timestamptz in a zone with DST. INTERVAL '1' YEAR is one year, but INTERVAL '1' means one second.
Query Result
1 SELECT date '2026-01-31' + interval '1 month'; 2026-02-28 00:00:00 (clamped to month end)
2 SET TimeZone = 'Europe/Berlin'; SELECT timestamptz '2026-03-28 12:00' + interval '1 day'; -- 2026-03-29 12:00+02: wall clock kept, only 23 hours later
3 SELECT * FROM events WHERE ts BETWEEN '2026-06-01' AND '2026-06-08'; -- includes 06-08 00:00:00 exactly
4 SELECT * FROM events WHERE ts >= '2026-06-01' AND ts < '2026-06-08'; -- correct half-open rangeReal scenarios: "last 30 days" reports across a DST change; a subscription renewing "monthly" on the 31st; billing periods as tstzrange; a date compared with a timestamp.
Fix: use half-open ranges, range types for periods, date_trunc in an explicit zone, and keep "business day" logic in one function.
numeric, money and floating point Must-know
In plain words: float is fast and approximate; numeric is exact and slower; money looks right and is not.
Common misunderstanding: "I will round at the end, so float is fine." Errors accumulate and can change a total by a cent; 0.1 + 0.2 <> 0.3 in binary floating point. The manual calls real and double precision "inexact, variable-precision numeric types" and says of numeric that it "is especially recommended for storing monetary amounts and other quantities where exactness is required", with the trade-off that arithmetic is "very slow compared to the integer types, or to the floating-point types".
Definition: numeric(p,s) has up to 131072 digits before the decimal point and 16383 after, and supports NaN and Infinity. money is a fixed-point type: the wiki says it "isn't actually very good for storing monetary values", it does not handle fractions of a cent, and it depends on the lc_monetary locale setting rather than storing a currency.
| Option | Exact | Currency stored | Speed | Use |
|---|---|---|---|---|
numeric(12,2) | Yes | No (add a column) | Slower | Default for money |
Integer minor units (bigint cents) + currency | Yes | Yes | Fastest | High volume; no rounding mode surprises; avoids Go and PHP float traps |
money | Mostly | No (locale) | Fast | Single-currency, add/subtract only |
real / double precision | No | No | Fast | Measurements, scores, never currency |
numeric without scale | Yes | No | Slower | Rarely right; fix the scale |
Step Result
1 SELECT 0.1::float8 + 0.2::float8 = 0.3::float8; false
2 SELECT 0.1::numeric + 0.2::numeric = 0.3::numeric; true
3 SELECT '12.345'::numeric(5,2); 12.35 (rounded half away from zero on input)
4 SELECT 10.00 / 3; 3.3333333333333333 (scale of a division result)Real scenarios: invoice totals; tax per line rounded then summed vs summed then rounded (a legal decision, store both rules); a wallet balance; a currency with zero decimals (JPY) or three (KWD), which is why integer minor units need a per-currency exponent.
Integer types: smallint, integer, bigint. A 32-bit integer primary key overflows at 2,147,483,647: tables with high insert rates should start at bigint (the migration to widen it later is painful, see Schema Migrations). Laravel's id() is a bigIncrements alias; MySQL UNSIGNED has no PostgreSQL equivalent.
Go and PHP:
// Package main shows the normalized schema and a safe way to read numeric.
package main
import (
"context"
"database/sql"
"fmt"
"math/big"
)
// Each fact lives in one place; money is exact; instants carry a zone.
var ddl = []string{
`CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE CHECK (email <> '')
)`,
`CREATE TABLE addresses (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers (id) ON DELETE RESTRICT,
street text NOT NULL,
city text NOT NULL,
postal_code text NOT NULL CHECK (char_length(postal_code) BETWEEN 3 AND 12)
)`,
`CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers (id) ON DELETE RESTRICT,
shipping_address_id bigint NOT NULL REFERENCES addresses (id) ON DELETE RESTRICT,
price numeric(12,2) NOT NULL CHECK (price >= 0),
paid_at timestamptz,
status text NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'paid', 'shipped', 'cancelled'))
)`,
}
// Money is an exact decimal read from a numeric column.
type Money struct{ r *big.Rat }
// ParseMoney converts the text form of numeric ("19.99") without a float hop.
func ParseMoney(s string) (Money, error) {
r, ok := new(big.Rat).SetString(s)
if !ok {
return Money{}, fmt.Errorf("invalid numeric %q", s)
}
return Money{r}, nil
}
func (m Money) Add(o Money) Money { return Money{new(big.Rat).Add(m.r, o.r)} }
// String renders two decimal places, the scale of numeric(12,2).
func (m Money) String() string { return m.r.FloatString(2) }
// OrderTotal scans numeric as a string: the driver never converts it to float64.
func OrderTotal(ctx context.Context, db *sql.DB, orderID int64) (Money, error) {
var raw string
err := db.QueryRowContext(ctx,
`SELECT price::text FROM orders WHERE id = $1`, orderID).Scan(&raw)
if err != nil {
return Money{}, err
}
return ParseMoney(raw)
}
func main() {
var sum Money
sum.r = new(big.Rat)
for i := 0; i < 10; i++ {
m, _ := ParseMoney("0.10")
sum = sum.Add(m)
}
fmt.Println(sum, len(ddl)) // 1.00 3
}Laravel: $table->decimal('price', 12, 2) and the cast 'price' => 'decimal:2' (a string, never a float), covered in Laravel migrations and casts.
text, varchar(n), char(n), citext and collations Must-know
In plain words: in PostgreSQL text is a string of any length, and varchar(n) is the same thing with a length check.
Common misunderstanding: "varchar(255) is faster or smaller." The manual says there is no performance difference among text, varchar and char(n) ("blank-padded") in PostgreSQL, and that in most situations text or character varying should be used instead of char(n); the 255 limit is a MySQL-era habit. The wiki: "Don't use the type varchar(n) by default. Consider varchar (without the length limit) or text instead."
Definition: text, varchar, varchar(n) (error if longer than n characters, not bytes), char(n) (blank-padded, wasteful, surprising comparisons). If you need a limit, a CHECK (char_length(x) <= n) can also express a minimum, a character set or a pattern; varchar(n) is the SQL-standard portable choice. Long values go out of line (TOAST, up to 1 GB).
Case-insensitive text: the citext extension stores text and compares it case-insensitively; the alternative is a unique index on lower(email) or a nondeterministic ICU collation. Collations decide sort order and equality: COLLATE "C" is byte order and fast; locale collations (en_US.UTF-8, ICU) sort linguistically and can change between OS versions, which silently corrupts indexes (reindex after upgrades; see Schema Migrations).
Real scenarios: emails (citext or lower() index); slugs (CHECK (slug ~ '^[a-z0-9-]+$')); a surname field varchar(20) rejecting a real customer; free-text notes (text).
| Engine | Strings |
|---|---|
| PostgreSQL | text = varchar performance; no 255 limit; encoding per database (use UTF8) |
| MySQL | Use utf8mb4 (real 4-byte UTF-8; utf8 is the 3-byte alias utf8mb3); VARCHAR(n) counts characters, row size limit of 65,535 bytes; default collations are case-insensitive (utf8mb4_0900_ai_ci) so UNIQUE ignores case |
| SQL Server | nvarchar for Unicode; varchar(max); collation decides case sensitivity |
| Oracle | VARCHAR2; '' equals NULL; byte vs char semantics |
| SQLite | TEXT affinity; length not enforced unless a CHECK is added |
| MongoDB | UTF-8 strings; collation per collection/index |
boolean Good to know
In plain words: boolean is true, false or null; make it NOT NULL DEFAULT false unless "unknown" is a real answer.
Common misunderstanding: "A nullable boolean is a flag." It is a three-state value, and WHERE NOT is_active skips the nulls. Do not model state with several booleans (is_paid, is_shipped, is_cancelled); one status column prevents impossible combinations.
Definition: PostgreSQL boolean accepts true/false/t/f/yes/no/on/off/1/0. MySQL's BOOLEAN is an alias for TINYINT(1). SQLite has no boolean storage class (0 and 1 integers). Oracle had no SQL boolean column type until recently (use NUMBER(1) or CHAR(1)). SQL Server uses bit.
inet and cidr Good to know
In plain words: native types for IP addresses (inet) and networks (cidr).
Common misunderstanding: "An IP address is a string." As a string you cannot ask "is this address inside that network" with an index, and '10.0.0.10' < '10.0.0.9' is a text comparison.
Definition: inet holds a host address with an optional netmask, cidr a network specification (host bits must be zero); both occupy 7 or 19 bytes and sort IPv4 before IPv6. Operators <<, <<= (contained in), >>, &&; indexes with gist (col inet_ops).
CREATE TABLE logins (user_id bigint NOT NULL, ip inet NOT NULL, at timestamptz NOT NULL DEFAULT now());
SELECT * FROM logins WHERE ip << '10.0.0.0/8';Laravel's ipAddress() creates a VARCHAR column; use DB::statement or a custom column type for real inet.
Generated columns Important
In plain words: a column computed from other columns of the same row, kept right by the database.
Common misunderstanding: "A generated column can aggregate other rows or call anything." It cannot reference other rows or non-immutable functions; for cross-row values use a trigger, a materialized view or a counter cache.
Definition: GENERATED ALWAYS AS (expression) STORED | VIRTUAL. The PostgreSQL manual: a stored generated column is computed when written and occupies storage; a virtual one occupies no storage and is computed when read; "a virtual generated column is similar to a view and a stored generated column is similar to a materialized view (except that it is always updated automatically)". In that manual virtual is the default, and a virtual column cannot use user-defined types or functions. In older PostgreSQL releases only STORED was available.
CREATE TABLE order_lines (
order_id bigint, product_id text,
qty integer NOT NULL, unit_price numeric(12,2) NOT NULL,
line_total numeric(14,2) GENERATED ALWAYS AS (qty * unit_price) STORED,
PRIMARY KEY (order_id, product_id)
);Laravel: ->storedAs('qty * unit_price') (MariaDB, MySQL, PostgreSQL, SQLite) and ->virtualAs(...) (MariaDB, MySQL, SQLite), from the migration column modifiers. MySQL generated columns are the way to index a JSON key.
Identity columns Important
GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY is the SQL-standard replacement for serial. The wiki: "For new applications, identity columns should be used instead" of serial, because serial types have behaviours "that make schema, dependency, and permission management unnecessarily cumbersome". MySQL's equivalent is AUTO_INCREMENT, SQL Server's IDENTITY(1,1), Oracle 12c+ GENERATED AS IDENTITY, SQLite INTEGER PRIMARY KEY [AUTOINCREMENT]. In Laravel 13, $table->id() is documented as an alias of bigIncrements; whether your PostgreSQL driver emits an identity or a serial-backed sequence is worth checking against the generated DDL (php artisan schema:dump or the SQL log) if it matters to you.
Binary, UUID and other types in brief Good to know
| Type | Note |
|---|---|
uuid | Native 16-byte type in PostgreSQL; MySQL stores BINARY(16) (use UUID_TO_BIN(uuid, 1) for time-ordering swap); SQL Server uniqueidentifier |
bytea / BLOB | Small binary only; large files belong in object storage with the key in the database |
hstore, ltree, tsvector, geometry | Extension types: key-value, trees, full-text search, PostGIS |
serial | Legacy auto-number, see identity columns |
xml | Avoid unless a standard demands it |
Per-engine behaviour
Matrix 1: type and feature support
| Feature | PostgreSQL | MySQL InnoDB | SQL Server | Oracle | SQLite | MongoDB | CockroachDB | Redis |
|---|---|---|---|---|---|---|---|---|
| Instant with zone | timestamptz | TIMESTAMP (UTC-converted) | datetimeoffset | TIMESTAMP WITH TIME ZONE | None (TEXT/REAL/INTEGER) | Date (UTC ms) | TIMESTAMPTZ | Unix time in a value |
| Exact decimal | numeric | DECIMAL | decimal | NUMBER | Stored as REAL/INTEGER (no exact decimal) | Decimal128 | DECIMAL | Strings |
| JSON | json, jsonb | JSON | nvarchar + functions | JSON (21c+) | JSON functions over TEXT | Native BSON | JSONB | RedisJSON module |
| Arrays | Yes | No | No | No (nested tables, VARRAY) | No | Yes | Yes | Lists, sets |
| Range types | Yes | No | No | No | No | No | No | No |
CHECK enforced | Yes | Yes (8.0) | Yes | Yes | Yes | $jsonSchema | Yes | No |
EXCLUDE | Yes | No | No | No | No | No | No | No |
| Deferrable constraints | Yes | No | No | Yes | FK only | No | No | No |
| Domains | CREATE DOMAIN | No | Alias types | 23ai | No | No | No | No |
| Generated columns | STORED (+ VIRTUAL in the current manual) | VIRTUAL or STORED | Computed columns | Virtual columns | VIRTUAL/STORED | Computed in the pipeline | STORED/VIRTUAL | No |
| Native enum | CREATE TYPE ... AS ENUM | ENUM | No | No | No | No | ENUM | No |
| Native UUID type | uuid | BINARY(16) | uniqueidentifier | RAW(16) | BLOB | UUID BSON subtype | UUID | String |
| Partial index | Yes | No (functional indexes only) | Filtered index | Function-based | Yes | Partial indexes | Yes | No |
| Transactional DDL | Yes | No (implicit commit) | Yes | No (implicit commit) | Yes | No | Yes (with limits) | No |
(Cells for non-PostgreSQL products are from my general knowledge of those products and were not re-read in saved sources for this page; the MySQL manual refuses automated fetching. Check the product's current docs before relying on a cell.)
What each database really does
| Product | Schema-design facts to remember |
|---|---|
| PostgreSQL | Strong constraints (CHECK, EXCLUDE, deferrable), rich types (arrays, ranges, jsonb, inet), transactional DDL, heap tables so PK choice affects only index locality; no automatic FK index |
| MySQL / InnoDB | Clustered primary key (random UUID PKs hurt the table and every secondary index); utf8mb4 not utf8; TIMESTAMP vs DATETIME; no deferrable or EXCLUDE; ENUM and JSON native; MyISAM has no foreign keys (see MySQL Storage Engines) |
| SQL Server | IDENTITY, uniqueidentifier, datetimeoffset, computed columns, "multiple cascade paths" limit on ON DELETE CASCADE; filtered indexes |
| Oracle | '' is NULL; NUMBER; DATE has a time part; identity columns from 12c; deferrable constraints; no ON UPDATE actions |
| SQLite | Flexible (dynamic) typing: any column accepts any value unless the table is STRICT; foreign keys off until PRAGMA foreign_keys = ON |
| MongoDB | Schema by convention; embed vs reference replaces normal forms; $jsonSchema validation; denormalization is the default |
| CockroachDB | PostgreSQL wire and types; sequential keys create hot ranges; UUID keys or hash-sharded indexes; ALTER is online |
| Redis | No schema; key naming and data-structure choice are the design; see Redis |
SQLite typing and STRICT tables Important
In plain words: SQLite lets you put text in an integer column.
Common misunderstanding: "INTEGER means the column only holds integers." In SQLite a declared type only sets an affinity (a preference): "Flexible typing is a feature of SQLite, not a bug", in the project's words. There are five storage classes (NULL, INTEGER, REAL, TEXT, BLOB), no boolean class and no date class; dates are stored as TEXT, REAL or INTEGER.
Definition: a STRICT table (as of SQLite 3.37.0, 2021-11-27) enforces that every column declares one of INT, INTEGER, REAL, TEXT, BLOB, ANY and that values are of that type or can be losslessly coerced by affinity rules.
Session 1
1 CREATE TABLE t (n INTEGER);
2 INSERT INTO t VALUES ('hello'); -- accepted
SELECT n, typeof(n) FROM t; -- hello | text
3 CREATE TABLE s (n INTEGER) STRICT;
4 INSERT INTO s VALUES ('hello'); -- Error: cannot store TEXT value in INTEGER column s.n
5 PRAGMA foreign_keys = ON; -- per connection, off by defaultReal scenario: an app database in SQLite where a bug wrote '' into a number column six months ago; STRICT plus CHECK and PRAGMA foreign_keys = ON makes SQLite behave like the others. Also: INTEGER PRIMARY KEY is an alias for the rowid.
MySQL type differences Important
| Topic | MySQL / InnoDB | PostgreSQL |
|---|---|---|
DATETIME vs TIMESTAMP | DATETIME: no conversion, range to year 9999. TIMESTAMP: stored as UTC, converted by session time_zone, range ends in 2038 | timestamp vs timestamptz; timestamptz ends far later |
| Character set | utf8mb4 is full UTF-8; utf8 means 3-byte utf8mb3: emoji fail or truncate | UTF8 encoding handles all code points |
| Case sensitivity | Default collation is case-insensitive and accent-insensitive | Case-sensitive by default; citext or lower() |
ENUM | Native, value list in the table definition | CREATE TYPE |
JSON | Binary JSON, no GIN; index through generated columns | jsonb with GIN |
UNSIGNED | Integer modifier | No unsigned |
| Booleans | Alias for TINYINT(1) | boolean |
| Auto IDs | AUTO_INCREMENT | Identity or sequence |
| Strict mode | STRICT_TRANS_TABLES makes truncation an error; legacy mode silently truncates (warning 1265) | Always an error |
| Constraints | CHECK enforced from 8.0 (error 3819); no deferrable | Full set |
(From my knowledge of MySQL; the manual returned HTTP 403 to automated fetch, so the table is unverified against a saved page.)
Mechanics
How constraints are enforced Important
PostgreSQL implements foreign keys with system triggers: an insert or update on the child runs a check against the parent that takes a FOR KEY SHARE lock; a delete or key update on the parent searches the child, which is a sequential scan unless the child column is indexed. That is why a missing FK index makes parent deletes slow and lock-heavy. Unique constraints and primary keys are backed by a unique B-tree; exclusion constraints by a GiST (or SP-GiST) index. NOT VALID adds a constraint without scanning existing rows (new writes are checked); VALIDATE CONSTRAINT scans later under a weaker lock, the zero-downtime recipe in Schema Migrations.
Session 1 Session 2
1 BEGIN;
2 INSERT INTO orders (customer_id) VALUES (7); -- takes FOR KEY SHARE on customers row 7
3 UPDATE customers SET name = 'x' WHERE id = 7; -- OK (a non-key update does not conflict)
4 DELETE FROM customers WHERE id = 7; -- waits for session 1
5 COMMIT;
6 -- delete now fails with 23503: an order references itError codes you will catch
| Condition | PostgreSQL SQLSTATE | MySQL error | Meaning | Retry? |
|---|---|---|---|---|
| Unique violation | 23505 | 1062 | Duplicate key; also the idempotency signal for ON CONFLICT | No, handle (return existing / 409) |
| Foreign key violation (child or parent) | 23503 | 1451 (parent), 1452 (child) | Missing parent or existing children | No |
| Not-null violation | 23502 | 1048 | Required value missing | No |
| Check violation | 23514 | 3819 | Row rule broken | No |
| Exclusion violation | 23P01 | not available | Overlap | No (or pick another slot) |
| Value too long | 22001 | 1406 | varchar(n) exceeded | No |
| Numeric out of range | 22003 | 1264 | Overflow of an integer or numeric | No |
| Invalid text representation | 22P02 | 1366 | Bad cast ('abc' to integer) | No |
Deferred constraint failed at COMMIT | 23503 / 23505 at commit | not available | The whole transaction aborts | Fix data, retry |
| Serialization failure | 40001 | 1213 (deadlock) | Concurrent write conflict, see Isolation Levels | Yes |
Knobs
| Setting | What it does |
|---|---|
SET TimeZone = 'UTC' (PostgreSQL) | Session zone used to display and interpret timestamptz |
lc_monetary | Decides how money is read and printed; the reason not to use it |
IntervalStyle | Output style of interval (postgres, iso_8601, sql_standard) |
SET CONSTRAINTS ALL DEFERRED | Defers deferrable constraints until commit |
default_toast_compression | Compression of large values such as jsonb and text |
sql_mode = STRICT_TRANS_TABLES (MySQL) | Truncation and bad values become errors |
time_zone (MySQL) | Zone used by TIMESTAMP conversion |
PRAGMA foreign_keys = ON (SQLite) | Enables FK enforcement per connection |
Storage details that affect design Good to know
PostgreSQL aligns column values to their type's boundary, so a table that interleaves boolean, bigint and boolean wastes padding bytes in every row; declare wide fixed-width columns (bigint, timestamptz, uuid) first, then 4-byte, then small ones, then variable-length. Rows over about 2 kB have their large values moved out of line (TOAST), so a hot narrow table is fast to scan and a jsonb blob is expensive to update. NULLs cost one bit each in the row's null bitmap, so nullable columns are cheap but not free. These matter at the scale of Database Internals and Billion-Row Tables, not in a 10,000-row table.
Solving the classic problems
A flat table that rots: before and after
The "before" is the demo that works and rots; the "after" is the same data with each fact once, exact money, instants with zones, real constraints.
Go, before: a flat orders row repeats the address, stores price as float64, writes a zoneless time.Time into timestamp and uses varchar(255) everywhere. The demo prints false because ten additions of 0.1 do not equal 1.0.
// Package main shows a schema that works in a demo and rots in production.
package main
import (
"fmt"
"time"
)
// Order repeats the address on every row, stores money as a binary float
// and keeps a wall-clock time with no zone attached.
type Order struct {
ID int64
CustomerName string
Street string // copied from the customer on every order
City string
PostalCode string
Price float64 // 0.1 + 0.2 != 0.3
PaidAt time.Time // written into a "timestamp" column, zone lost
Status string
}
const ddl = `
CREATE TABLE orders (
id serial PRIMARY KEY,
customer_name varchar(255),
street varchar(255),
city varchar(255),
postal_code varchar(255),
price double precision,
paid_at timestamp,
status varchar(255)
);`
func main() {
var total float64
for i := 0; i < 10; i++ {
total += 0.1
}
fmt.Println(total == 1.0, total) // false 0.9999999999999999
fmt.Println(len(ddl) > 0)
}Go, after: addresses live in their own table referenced with ON DELETE RESTRICT; money is numeric(12,2) read as text and parsed with math/big.Rat; instants are timestamptz; primary keys are bigint identity.
(The "after" Go file is the one imported in numeric, money and floating point.)
Laravel, before: a migration with float('price'), a zoneless timestamp, string() (a varchar(255)) for everything and address columns copied onto each order.
<?php
// database/migrations/2026_01_01_000000_create_orders_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->string('customer_name'); // varchar(255) by habit
$table->string('street'); // address copied onto every order
$table->string('city');
$table->string('postal_code');
$table->float('price'); // binary floating point for money
$table->timestamp('paid_at')->nullable(); // no time zone on Postgres
$table->string('status'); // any string is accepted
$table->timestamps();
});
}
};Laravel, after: decimal('price', 12, 2), timestampTz, foreignId()->constrained()->restrictOnDelete(), a raw CHECK through DB::statement and jsonb for sparse extras.
<?php
// database/migrations/2026_01_01_000000_create_orders_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('addresses', function (Blueprint $table) {
$table->id();
$table->foreignId('customer_id')->constrained()->restrictOnDelete();
$table->text('street');
$table->text('city');
$table->text('postal_code');
$table->timestampsTz();
});
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->foreignId('customer_id')->constrained()->restrictOnDelete();
$table->foreignId('shipping_address_id')
->constrained('addresses')
->restrictOnDelete();
$table->decimal('price', 12, 2);
$table->timestampTz('paid_at')->nullable();
$table->text('status')->default('pending');
$table->jsonb('meta')->nullable();
$table->timestampsTz();
});
// The schema builder has no CHECK helper, so use raw SQL.
DB::statement(
"ALTER TABLE orders ADD CONSTRAINT orders_status_check
CHECK (status IN ('pending', 'paid', 'shipped', 'cancelled'))"
);
DB::statement('ALTER TABLE orders ADD CONSTRAINT orders_price_check CHECK (price >= 0)');
}
};Go: NULL handling and struct mapping
In plain words: a Go string cannot be NULL, so scanning a NULL into it fails.
Common misunderstanding: "Scan NULL into a plain string and you get ""." You get an error (converting NULL to string is unsupported), and the opposite mistake, writing "" where you meant NULL, stores a real empty string that no IS NULL check finds.
Definition: database/sql offers sql.NullString, sql.NullInt64, sql.NullTime, sql.NullBool, sql.NullFloat64 and the generic sql.Null[T] (a struct with V and Valid); pointers (*string) also scan NULL as nil. sql.Null* types are not JSON-friendly (they marshal as {"String":...,"Valid":...}), so map to pointers or omitempty DTOs at the API boundary.
| Representation | Reads NULL | Writes NULL | JSON | When |
|---|---|---|---|---|
sql.NullString etc. | .Valid == false | NullString{} | Awkward | Repository layer, explicit |
sql.Null[T] | .Valid == false | Null[T]{} | Awkward | Any scannable type, less boilerplate |
*string | nil | nil | Natural | DTOs, optional fields |
COALESCE(col, '') in SQL | Never NULL | n/a | Natural | When absent and empty are the same by definition |
pgtype (pgx) | .Valid | .Valid=false | Package-specific | pgx users |
// Package main shows three ways to read a nullable column in Go.
package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"time"
)
// Profile mixes the three representations of "this column may be NULL".
type Profile struct {
ID int64
Nickname sql.NullString // classic: check .Valid before .String
BirthDate sql.Null[time.Time] // generic form, any scannable type
Phone *string // pointer: nil means NULL, easy to marshal
}
// Load reads one row; a NULL never turns into "" or the zero time silently.
func Load(ctx context.Context, db *sql.DB, id int64) (Profile, error) {
p := Profile{ID: id}
err := db.QueryRowContext(ctx,
`SELECT nickname, birth_date, phone FROM profiles WHERE id = $1`, id).
Scan(&p.Nickname, &p.BirthDate, &p.Phone)
return p, err
}
// Display applies the NULL policy in one place.
func (p Profile) Display() string {
if p.Nickname.Valid {
return p.Nickname.String
}
return "anonymous"
}
// SetNickname writes NULL for an empty string instead of storing ”.
func SetNickname(ctx context.Context, db *sql.DB, id int64, nick string) error {
v := sql.NullString{String: nick, Valid: nick != ""}
_, err := db.ExecContext(ctx, `UPDATE profiles SET nickname = $1 WHERE id = $2`, v, id)
return err
}
func main() {
nick := sql.NullString{String: "ada", Valid: true}
b, _ := json.Marshal(nick)
fmt.Println(string(b)) // {"String":"ada","Valid":true}: sql.Null* is not JSON-friendly
phone := "555-0100"
b, _ = json.Marshal(Profile{ID: 1, Phone: &phone})
fmt.Println(string(b)) // pointers marshal to the value or null
}Struct mapping rules: the zero value of a Go struct field is not NULL; time.Time{} is year 1, not "unset"; scan numeric as string (or shopspring/decimal) and never float64; use RETURNING id; use pgx.CollectRows with RowToStructByName or sqlx struct tags (db:"customer_id") so column order changes do not break scans.
Laravel: migrations and casts
In plain words: the migration defines the database types, the model's casts() tell Eloquent how to convert them to PHP types.
Common misunderstanding: "A cast creates a constraint." A cast only converts on read and write; the database still accepts whatever the column type allows. The decimal:2 cast returns a string, deliberately: PHP floats have the same problem as Go's.
Definition: the Laravel 13 schema builder methods used on this page: id() (alias of bigIncrements), foreignId() (an unsigned bigint) with constrained(), cascadeOnDelete(), restrictOnDelete(), nullOnDelete(), noActionOnDelete(), cascadeOnUpdate(), restrictOnUpdate(); decimal(), timestampTz(), timestampsTz(), softDeletes()/softDeletesTz(), jsonb(), enum(), ulid(), uuid(), morphs(), ipAddress(), primary([...]), storedAs(), virtualAs(). Casts: decimal:2, immutable_datetime, array/AsArrayObject, backed enums, encrypted, hashed.
<?php
// app/Models/Order.php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\AsArrayObject;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected function casts(): array
{
return [
'price' => 'decimal:2', // string "19.99", never a float
'paid_at' => 'immutable_datetime',
'meta' => AsArrayObject::class, // jsonb for sparse extras only
];
}
}The migration for constraints the schema builder does not wrap (a CHECK, an EXCLUDE, a partial unique index) uses raw statements, with composite primary key, generated column, soft deletes and ON DELETE actions:
<?php
// database/migrations/2026_02_01_000000_add_constraints.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('rooms', function (Blueprint $table) {
$table->id();
$table->text('name');
});
Schema::create('bookings', function (Blueprint $table) {
$table->id();
$table->foreignId('room_id')->constrained()->restrictOnDelete();
$table->timestampTz('starts_at');
$table->timestampTz('ends_at');
$table->text('status')->default('held');
$table->text('reference');
$table->softDeletesTz(); // deleted_at timestamptz NULL
$table->timestampsTz();
});
Schema::create('order_lines', function (Blueprint $table) {
$table->foreignId('order_id')->constrained()->cascadeOnDelete(); // owned by the order
$table->foreignId('product_id')->constrained()->restrictOnDelete();
$table->unsignedInteger('qty');
$table->decimal('unit_price', 12, 2);
$table->decimal('line_total', 14, 2)->storedAs('qty * unit_price'); // generated column
$table->primary(['order_id', 'product_id']); // composite key
});
// Things the schema builder does not wrap: use raw DDL on PostgreSQL.
DB::statement('CREATE EXTENSION IF NOT EXISTS btree_gist');
DB::statement('ALTER TABLE bookings ADD CONSTRAINT bookings_window_check CHECK (ends_at > starts_at)');
DB::statement(
"ALTER TABLE bookings ADD CONSTRAINT bookings_no_overlap
EXCLUDE USING gist (room_id WITH =, tstzrange(starts_at, ends_at) WITH &&)
WHERE (deleted_at IS NULL)"
);
// Soft deletes and uniqueness: a reference is unique only among live rows.
DB::statement('CREATE UNIQUE INDEX bookings_reference_live_idx ON bookings (reference) WHERE deleted_at IS NULL');
}
};Eloquent conventions and the model for the same tables, with soft deletes, an enum cast and a counter cache:
<?php
// app/Models/Order.php and app/Enums/OrderStatus.php (shown together)
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
enum OrderStatus: string
{
case Pending = 'pending';
case Paid = 'paid';
case Shipped = 'shipped';
case Cancelled = 'cancelled';
}
class Order extends Model
{
use SoftDeletes; // deleted_at; every query adds WHERE deleted_at IS NULL
protected function casts(): array
{
return [
'status' => OrderStatus::class, // text + CHECK in the database, enum in PHP
'price' => 'decimal:2', // string, never float
'paid_at' => 'immutable_datetime',
'meta' => 'array', // jsonb for sparse extras
];
}
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class);
}
public function lines(): HasMany
{
return $this->hasMany(OrderLine::class);
}
}
class Customer extends Model
{
// Counter cache: increment atomically in SQL, never read-modify-write in PHP.
public static function bumpOrders(int $customerId, int $cents): void
{
DB::table('customers')->where('id', $customerId)->incrementEach([
'orders_count' => 1,
'spent_cents' => $cents,
]);
}
}
// order_lines has a composite primary key (order_id, product_id), so the model declares no single key.
// It is fine for reading through $order->lines; write lines through the query builder or the relation.
class OrderLine extends Model
{
public $incrementing = false;
protected $primaryKey = null;
public $timestamps = false;
}Eloquent conventions to know: the table name is the snake-case plural of the class (Flight to flights); the primary key is id, an incrementing integer, unless you use HasUuids (UUIDv7 by default in the Laravel 13 docs) or HasUlids; Eloquent expects created_at and updated_at and sets them; SoftDeletes needs deleted_at; a belongsTo(Customer) looks for customer_id. Changing columns on a live table is a migration problem: see Zero-Downtime Schema Migrations.
Soft deletes with unique constraints
The recipe: deleted_at timestamptz plus a partial unique index WHERE deleted_at IS NULL, an Eloquent SoftDeletes scope, and a nightly purge. In MySQL there are no partial indexes: use a generated column (email_live = IF(deleted_at IS NULL, email, NULL)) with a unique index, since unique indexes allow many NULLs.
Money, end to end
numeric(12,2) (or bigint cents + char(3) currency) in the column, decimal:2 cast in Laravel, string/big.Rat in Go, CHECK (price >= 0), a rounding rule written once (round per line, then sum), and prices on order lines as snapshots.
Instants end to end
timestamptz in the column, UTC in the application, immutable_datetime in Laravel, time.Time in Go, user zone stored as an IANA name, half-open ranges in queries.
Choosing
| Situation | Choose | Extra technique | Reason |
|---|---|---|---|
| New OLTP table | 3NF, surrogate bigint identity, natural key UNIQUE, FKs, NOT NULL | CHECK for domain rules | Correct by default |
| Rows created offline or by many services | UUIDv7 / ULID primary key | Public id = key | No coordination, locality |
| Public identifiers | Opaque uuid/ULID beside internal bigint | UNIQUE | Do not leak counts |
| Status with few stable values | text + CHECK or native enum | Backed enum in code | Simple |
| Status with labels, order, activity | Lookup table + FK | Translations beside | Data not DDL |
| Slow read of an aggregate | Counter cache + drift query | Sharded counter if hot | Measured benefit |
| Dashboard of heavy aggregates | Materialized view CONCURRENTLY | Unique index | Accept staleness |
| Booking, scheduling | EXCLUDE on a range | btree_gist | Atomic overlap check |
| Optional many attributes | jsonb + GIN | Promote hot keys to columns | Schema where you need it |
| Open-ended catalogue | jsonb or a document store | Core columns for filters | EAV is the worst of both |
| Polymorphic target | One FK per target + CHECK | Or polymorphic + morph map + orphan job | Integrity |
| Delete with undo | deleted_at + partial unique | Purge job | Uniqueness holds |
| Money | numeric(12,2) or integer cents + currency | Rounding rule | Exact |
| Event time | timestamptz | Zone name for local future events | An instant |
| Multi-tenant shared tables | tenant_id first in keys + composite FKs | RLS | Isolation |
| Very large append-only table | Partition by time | Partition key in the PK | Pruning, cheap retention |
In architecture: from a single process to a distributed system
Schema design is the longest-lived decision in a system: code is rewritten, tables remain. Normalized OLTP tables are the source of truth; denormalized shapes (read models, search indexes, warehouses) are derived from them and can be rebuilt. The design question across scales is: where do my constraints and my single copy of each fact live, and what happens when they cross a boundary?
Monolith: one process, one database
How it shows up: every rule can be a constraint, and foreign keys connect everything. Joins are cheap; normalization is the default.
Simplest correct usage: 3NF tables, surrogate keys, FKs, NOT NULL, CHECK, timestamptz, and a counter cache or a materialized view only after EXPLAIN shows the problem.
Example (simple): a shop: customers, addresses, orders, order_lines, products, with order_lines.unit_price as a snapshot and orders.total computed in the same transaction.
Example (complex): a clinic scheduler: appointments(doctor_id, during tstzrange) with an EXCLUDE constraint, deleted_at with a partial unique index, a version column for optimistic locking, and a tenant-scoped composite key.
Modular monolith and multiple databases
How it shows up: modules own tables, possibly in separate schemas. Foreign keys inside a module stay; across modules, reference by id without a database FK, or keep one FK if they share a database and accept the coupling.
Example: Billing references customers.id from CRM: a plain bigint customer_id with no FK, validated on write through the module's public interface, and a nightly job that finds dangling ids.
Rules: one module owns each table; the other modules read it through a view or an API; never JOIN another module's tables in application queries.
Microservices: foreign keys stop at the boundary
What survives: each service's local constraints and normalization. What does not: cross-service foreign keys, ON DELETE CASCADE across services and cross-service transactions. Referential integrity becomes an application and event concern: a customer.deleted event lets the order service decide what to do, with idempotent handlers and reconciliation jobs.
CRM service Orders service Search service
1 DELETE customer 7 (soft) 2 consume customer.deleted(7)
INSERT outbox(customer.deleted) UPDATE orders SET customer_status = 'closed' -- local denormalized copy
INSERT outbox(order.updated)
3 consume order.updated -> reindex document
-- each copy is a derived, rebuildable representation; the CRM row is the source of truthDenormalization across services: an orders.customer_name snapshot or a local customers_ref(id, name, status) replicated from events replaces the join you cannot do. IDs must be globally unique without coordination, which is where UUIDv7/ULID wins; see ID Generation at Scale and the outbox pattern.
Distributed data: replicas, caches and sharding
- Read replicas: a replica applies the same schema changes, but with delay; a column added on the primary is invisible on a lagging replica, so migrations must be backwards-compatible (Schema Migrations, Replication & Failover).
- Caches: a cached denormalized object is another copy with no drift query; give it a TTL and invalidate after commit.
- Sharding: foreign keys and unique constraints across shards do not exist; choose a shard key that keeps related rows together (
tenant_id), keep the key in every PK, and use globally unique ids (UUIDv7, snowflake) so rows can move. On CockroachDB sequential keys create hot ranges; use UUIDs or hash-sharded indexes (Partitioning & Sharding). - Time: clock skew between app servers makes
created_atfrom the application an unreliable ordering; use the database clock (now()default) for ordering,timestamptzfor storage.
Scaling path: 1x, 10x, 100x
| Load | What changes | Schema consequence |
|---|---|---|
| 1x (one primary, modest data) | 3NF, FKs, constraints, defaults | Correctness is cheap; spend effort on types and constraints |
| 10x (hot rows, big reports, replicas) | Counters and aggregates dominate reads; indexes grow | Counter cache, materialized view, FK indexes, bigint keys, jsonb hot keys promoted to columns, archive soft-deleted rows |
| 100x (partitioning, sharding, services) | Tables too big for one node; many writers | Partition keys inside every PK, tenant columns first, UUIDv7/ULID ids, cross-service integrity by events and reconciliation, read models rebuilt from the source |
At every step the rule holds: keep one source of truth per fact, make every copy derived and reconcilable, and push each invariant down to the lowest layer that can enforce it for every writer.
Lab
Normalize a messy orders CSV into 3NF, then denormalize one read path and measure it. The lab runs on SQLite because it needs no server: every number and output below was produced with SQLite 3.54.0 on one laptop, and your timings will differ. The same SQL works on PostgreSQL with the substitutions listed at the end; the PostgreSQL variant was not executed for this page.
Setup. Save this as messy.csv. It breaks 1NF (lists in cells), 2NF (product name depends on part of the key) and 3NF (customer city depends on the customer, country on the city).
order_id,order_date,customer_name,customer_email,customer_city,customer_country,product_ids,product_names,qty_list,unit_prices
1001,2026-03-01,Ada Lovelace,ada@example.com,London,UK,"P1;P2","Keyboard;Mouse","1;2","49.90;19.90"
1002,2026-03-02,Alan Turing,alan@example.com,Wilmslow,UK,P1,Keyboard,1,49.90
1003,2026-03-02,Ada Lovelace,ada@example.com,London,UK,P3,Monitor,1,189.00
1004,2026-03-03,Grace Hopper,grace@example.com,Arlington,US,"P2;P3","Mouse;Monitor","3;1","19.90;189.00"Experiment 1: 1NF, one row per order line. Open sqlite3 lab.db, import the CSV and split the ; lists with json_each, zipping them by position:
.headers on
.mode column
CREATE TABLE messy (order_id INT, order_date TEXT, customer_name TEXT, customer_email TEXT,
customer_city TEXT, customer_country TEXT, product_ids TEXT, product_names TEXT, qty_list TEXT, unit_prices TEXT);
.mode csv
.import --skip 1 messy.csv messy
.mode column
CREATE TABLE flat AS
SELECT m.order_id, m.order_date, m.customer_name, m.customer_email, m.customer_city, m.customer_country,
json_extract('["'||replace(m.product_ids,';','","')||'"]', '$['||p.key||']') AS product_id,
json_extract('["'||replace(m.product_names,';','","')||'"]', '$['||p.key||']') AS product_name,
CAST(json_extract('["'||replace(m.qty_list,';','","')||'"]', '$['||p.key||']') AS INTEGER) AS qty,
json_extract('["'||replace(m.unit_prices,';','","')||'"]', '$['||p.key||']') AS unit_price
FROM messy m, json_each('["'||replace(m.product_ids,';','","')||'"]') p;
SELECT * FROM flat;
-- order_id order_date customer_name customer_email customer_city customer_country product_id product_name qty unit_price
-- 1001 2026-03-01 Ada Lovelace ada@example.com London UK P1 Keyboard 1 49.90
-- 1001 2026-03-01 Ada Lovelace ada@example.com London UK P2 Mouse 2 19.90
-- 1002 2026-03-02 Alan Turing alan@example.com Wilmslow UK P1 Keyboard 1 49.90
-- 1003 ... (6 rows in total: 4 orders, 6 lines)Experiment 2: 2NF and 3NF, split into tables. Money becomes integer cents; foreign keys are switched on (SQLite needs the pragma); the update anomaly disappears:
PRAGMA foreign_keys = ON;
CREATE TABLE cities (id INTEGER PRIMARY KEY, name TEXT NOT NULL, country_code TEXT NOT NULL, UNIQUE (name, country_code));
CREATE TABLE customers (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE, name TEXT NOT NULL,
city_id INTEGER NOT NULL REFERENCES cities (id));
CREATE TABLE products (id TEXT PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES customers (id) ON DELETE RESTRICT,
ordered_on TEXT NOT NULL);
CREATE TABLE order_lines (order_id INTEGER NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
product_id TEXT NOT NULL REFERENCES products (id) ON DELETE RESTRICT,
qty INTEGER NOT NULL CHECK (qty > 0),
unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents >= 0),
PRIMARY KEY (order_id, product_id));
INSERT INTO cities (name, country_code) SELECT DISTINCT customer_city, customer_country FROM flat;
INSERT INTO customers (email, name, city_id)
SELECT DISTINCT f.customer_email, f.customer_name, c.id FROM flat f
JOIN cities c ON c.name = f.customer_city AND c.country_code = f.customer_country;
INSERT INTO products (id, name) SELECT DISTINCT product_id, product_name FROM flat;
INSERT INTO orders (id, customer_id, ordered_on)
SELECT DISTINCT f.order_id, cu.id, f.order_date FROM flat f JOIN customers cu ON cu.email = f.customer_email;
INSERT INTO order_lines
SELECT order_id, product_id, qty, CAST(round(CAST(unit_price AS REAL) * 100) AS INTEGER) FROM flat;
-- cities 3 | customers 3 | products 3 | orders 4 | lines 6
-- Ada moves: one row changes, not every order she ever placed
INSERT INTO cities (name, country_code) VALUES ('Paris', 'FR');
UPDATE customers SET city_id = (SELECT id FROM cities WHERE name = 'Paris') WHERE email = 'ada@example.com';
-- the database refuses an orphan:
DELETE FROM customers WHERE email = 'ada@example.com';
-- Error: FOREIGN KEY constraint failedExperiment 3: volume and the slow read path. Generate 5,000 customers, 200,000 orders and about 600,000 lines, then run the read path "top 20 customers by orders and total spent" on the normalized tables (this is the measured baseline):
PRAGMA foreign_keys = OFF;
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 5000)
INSERT INTO customers (id, email, name, city_id) SELECT 100 + i, 'user' || i || '@example.com', 'User ' || i, 1 FROM n;
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 200000)
INSERT INTO orders (id, customer_id, ordered_on)
SELECT 10000 + i, 100 + 1 + (i * 7919) % 5000, date('2026-01-01', '+' || (i % 300) || ' days') FROM n;
INSERT INTO products (id, name)
SELECT 'X' || i, 'Product ' || i FROM (WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 200) SELECT i FROM n);
INSERT INTO order_lines (order_id, product_id, qty, unit_price_cents)
SELECT o.id, 'X' || (1 + (o.id + k.k * 67) % 200), 1 + (o.id + k.k) % 4, 500 + ((o.id * k.k) % 9000)
FROM orders o, (SELECT 1 AS k UNION ALL SELECT 2 UNION ALL SELECT 3) k WHERE o.id > 10000;
PRAGMA foreign_keys = ON;
CREATE INDEX orders_customer_idx ON orders (customer_id);
ANALYZE;
.timer on
SELECT cu.id, count(DISTINCT o.id) AS orders, sum(l.qty * l.unit_price_cents) AS spent_cents
FROM customers cu JOIN orders o ON o.customer_id = cu.id JOIN order_lines l ON l.order_id = o.id
GROUP BY cu.id ORDER BY spent_cents DESC LIMIT 20;
-- Run Time: real 0.69 s (200,004 orders, 600,006 lines)Experiment 4: denormalize that one read path, measure again, measure the write cost. A customer_stats counter-cache table, filled once, then kept honest by two triggers:
-- baseline write cost, no triggers yet: 20,000 orders and one line each
CREATE TEMP TABLE batch AS WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 20000) SELECT i FROM n;
.timer on
INSERT INTO orders (id, customer_id, ordered_on) SELECT 500000 + i, 101 + i % 5000, '2026-12-01' FROM batch;
INSERT INTO order_lines SELECT 500000 + i, 'X1', 1, 1000 FROM batch;
-- Run Time: real 0.014 s (orders) real 0.0034 s (lines)
.timer off
CREATE TABLE customer_stats (customer_id INTEGER PRIMARY KEY REFERENCES customers (id),
order_count INTEGER NOT NULL DEFAULT 0, spent_cents INTEGER NOT NULL DEFAULT 0);
INSERT INTO customer_stats
SELECT o.customer_id, count(DISTINCT o.id), sum(l.qty * l.unit_price_cents)
FROM orders o JOIN order_lines l ON l.order_id = o.id GROUP BY o.customer_id;
CREATE INDEX customer_stats_spent_idx ON customer_stats (spent_cents DESC);
CREATE TRIGGER orders_ai AFTER INSERT ON orders BEGIN
INSERT INTO customer_stats (customer_id, order_count) VALUES (NEW.customer_id, 1)
ON CONFLICT (customer_id) DO UPDATE SET order_count = order_count + 1;
END;
CREATE TRIGGER lines_ai AFTER INSERT ON order_lines BEGIN
UPDATE customer_stats SET spent_cents = spent_cents + NEW.qty * NEW.unit_price_cents
WHERE customer_id = (SELECT customer_id FROM orders WHERE id = NEW.order_id);
END;
.timer on
SELECT customer_id, order_count, spent_cents FROM customer_stats ORDER BY spent_cents DESC LIMIT 20;
-- Run Time: real 0.000036 s (the same top 20 was 0.69 s from the normalized tables)
.timer off
EXPLAIN QUERY PLAN SELECT customer_id, order_count, spent_cents FROM customer_stats ORDER BY spent_cents DESC LIMIT 20;
-- SCAN customer_stats USING INDEX customer_stats_spent_idx
-- write cost with the triggers: insert another 20,000 orders (triggers fire), then time the lines
INSERT INTO orders (id, customer_id, ordered_on) SELECT 600000 + i, 101 + i % 5000, '2026-12-02' FROM batch;
.timer on
INSERT INTO order_lines SELECT 600000 + i, 'X1', 1, 1000 FROM batch;
-- Run Time: real 0.018 s (lines; was 0.0034 s without the trigger)
.timer off
-- drift query (see "The drift query"), counting disagreeing customers:
-- drifting = 0What the numbers say (SQLite 3.54.0, one run each, indicative only): the read dropped from about 0.69 s to about 36 microseconds (the plan is an index scan on customer_stats_spent_idx), and the write of 20,000 lines became about five times slower (0.0034 s to 0.018 s), which is a cost paid per write for a benefit paid per read. The trade is good only if the read path is hot; with the triggers removed the copy drifts as soon as someone edits a line, so keep the drift query.
On PostgreSQL: replace INTEGER PRIMARY KEY with bigint GENERATED ALWAYS AS IDENTITY, .import with \copy messy FROM 'messy.csv' CSV HEADER, json_extract/json_each with string_to_array and unnest(... , ...) WITH ORDINALITY, triggers with a PL/pgSQL function (see the trigger example), .timer on with \timing on and look at EXPLAIN (ANALYZE, BUFFERS). Expected shape: the baseline is a hash join with a sort over about 600,000 lines; the denormalized read is an index scan on customer_stats_spent_idx; the write path pays the trigger. Run it before trusting any number.
Common misconceptions
| Belief | Reality |
|---|---|
| "Normalize everything to the highest form" | 3NF/BCNF is the practical target; each further form removes rarer anomalies and adds joins; denormalize deliberately where measured |
| "UUID primary keys are always slow" | Random UUIDv4 scatters inserts; UUIDv7/ULID are time-ordered and close to bigint for locality |
"timestamptz stores the time zone" | It stores an instant as UTC; the zone is a session display setting |
"varchar(255) is better than text" | No performance difference in PostgreSQL; use text plus CHECK where a limit is real |
"float is fine for money if I round" | Errors accumulate; use numeric or integer minor units |
"NULL = NULL is true" | It is unknown; use IS NULL and IS DISTINCT FROM |
"UNIQUE allows one NULL" | PostgreSQL allows many unless NULLS NOT DISTINCT; SQL Server allows one |
| "Foreign keys are enforced in SQLite by default" | They are off until PRAGMA foreign_keys = ON on each connection |
"jsonb means I do not need a schema" | The schema moved to application code unchecked; keys you filter on are columns |
| "Soft delete is a safe delete" | It breaks uniqueness, leaks through forgotten filters and is not erasure |
| "A polymorphic association is a foreign key" | There is no FK, so orphans are possible |
"CASCADE is convenient" | It deletes silently and widely; use it only for true ownership |
| "An ORM cast enforces types" | It converts in PHP; the database column type and constraints enforce |
"MySQL utf8 is UTF-8" | It is utf8mb3; use utf8mb4 |
Cheat sheet
| Topic | What to remember |
|---|---|
| Normal forms | 1NF atomic; 2NF whole key; 3NF nothing but the key; BCNF every determinant a key; 4NF/5NF rare |
| Anomalies | Update, insert, delete: all from the same fact stored twice |
| Denormalize | Measure first; one source, one refresh mechanism, one drift query |
| Counter cache | SET n = n + 1 in the same transaction; never read-modify-write |
| Keys | Surrogate PK + natural UNIQUE; identity bigint default; UUIDv7/ULID for distributed writers |
| Composite key | Column order = index order; join tables use (a, b) as PK |
| Foreign key | Index the child column; RESTRICT default, CASCADE only for ownership |
| Deferrable | DEFERRABLE INITIALLY DEFERRED; checked at COMMIT (PostgreSQL, Oracle) |
CHECK / EXCLUDE | Row rules and overlap rules in the database; NULL passes a CHECK |
| NULL | Three-valued logic; avoid NOT IN (subquery); NOT NULL by default |
| Time | timestamptz, UTC in app, zone name separately, half-open ranges |
| Money | numeric(12,2) or integer cents + currency; never float, avoid money |
| Text | text + CHECK; citext or lower() for emails; utf8mb4 in MySQL |
| JSONB | Sparse and foreign shapes; hot keys become columns; GIN jsonb_path_ops for @> |
| Polymorphic / EAV | Prefer an FK per target; EAV loses types and constraints |
| Soft delete | Partial unique index, global scope, purge job |
| Go NULLs | sql.Null[T], sql.NullString, or *T; scan numeric as string |
| Laravel | decimal:2, timestampTz, constrained()->restrictOnDelete(), raw CHECK |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A table order_lines(order_id, product_id, product_name, qty) has the key (order_id, product_id). Which normal form does it violate and how do you fix it? Must-know
Answer
Answer: 2NF: product_name depends on product_id alone, part of the key. Move it to products(id, name) and keep a foreign key from order_lines.product_id. See 2NF.
2 — What is the difference between 3NF and BCNF, and when do they differ? Good to know
Answer
Answer: 3NF allows a determinant that is not a key if the dependent attribute is prime; BCNF requires every determinant to be a candidate key. They differ only with overlapping candidate keys. See BCNF.
3 — Why is an application-side read, add one, write back unsafe for a counter cache? Must-know
Answer
Answer: Two concurrent requests both read the same value and both write value + 1: a lost update. Use SET n = n + 1 inside the same transaction. See Counter cache.
4 — Name two reasons a random UUIDv4 primary key costs more than a bigint identity in MySQL InnoDB. Important
Answer
Answer: The table is the primary-key B+tree, so random inserts split pages across the whole table; and every secondary index stores the primary key, so a 16-byte random key enlarges every index. See Choosing the surrogate.
5 — A foreign key is declared ON DELETE CASCADE; the parent has 10 million children. What goes wrong? Important
Answer
Answer: One DELETE becomes a huge, long transaction that locks and logs millions of rows, and without an index on the child column it scans the child table. See Foreign keys.
6 — When is a deferrable constraint needed? Good to know
Answer
Answer: When statements inside a transaction temporarily violate a rule that holds at commit: circular references, swapping unique values, out-of-order bulk loads. See Deferrable constraints.
7 — SELECT * FROM a WHERE id NOT IN (SELECT a_id FROM b) returns no rows although some should match. Why? Must-know
Answer
Answer: One b.a_id is NULL: id NOT IN (..., NULL) is never true. Use NOT EXISTS. See NULL logic.
8 — A CHECK (price >= 0) accepted a row with price = NULL. Why, and what fixes it? Must-know
Answer
Answer: NULL >= 0 is unknown, and a CHECK rejects only FALSE. Add NOT NULL. See CHECK.
9 — Why can a polymorphic association leave orphans, and what are two alternatives? Important
Answer
Answer: The database cannot put a foreign key on a column whose target table varies. Use one nullable FK per target with a CHECK that exactly one is set, or a join table per target. See Polymorphic associations.
10 — A user in Tehran enters an appointment at "09:00 next March 1". What do you store and why? Must-know
Answer
Answer: The local timestamp (or date and time) and the IANA zone name, because the UTC offset for a future local time can change by law; compute the timestamptz instant when needed. See timestamptz.
11 — In Go, what happens if you Scan a NULL into a plain string, and what are the three safe options? Important
Answer
Answer: Scan returns an error. Use sql.NullString (or sql.Null[T]), a *string, or COALESCE in SQL when absent equals empty. See Go: NULL handling.
12 — Your lab read dropped from 0.69 s to microseconds after a counter cache. What did you pay, and what keeps it honest? Important
Answer
Answer: A slower write (extra trigger work per insert) and a copy that can drift; a drift query that recomputes from the source and alerts on any difference keeps it honest. See the Lab and The drift query.
Glossary
| Term | Meaning |
|---|---|
| Functional dependency (FD) | X -> Y: knowing X fixes Y |
| Determinant | The left side of a functional dependency |
| Superkey | A set of columns unique across rows |
| Candidate key | A minimal superkey |
| Primary key | The chosen candidate key |
| Alternate key | A candidate key not chosen as primary |
| Prime attribute | A column that is part of some candidate key |
| Closure | Every attribute a set of columns determines |
| 1NF | Atomic cells, no repeating groups |
| 2NF | No partial dependency on a composite key |
| 3NF | No transitive dependency of a non-key on the key |
| BCNF | Every determinant is a candidate key |
| 4NF | No non-trivial multivalued dependency except on a key |
| 5NF | Every join dependency implied by candidate keys |
| Multivalued dependency (MVD) | Independent set of values for one key (X ->> Y) |
| Join dependency | A table equals the join of its projections |
| Update / insert / delete anomaly | Inconsistency or loss caused by duplicated facts |
| Denormalization | Deliberate stored copy of a derivable value |
| Materialized view | Stored query result, refreshed on demand |
| Counter cache | Aggregate column maintained with the writes |
| Trigger | Code run by the database on a row change |
| Drift query | A query that finds copies that disagree with the source |
| Snapshot column | Value copied at a moment and never updated |
| Surrogate key | Meaningless generated identifier |
| Natural key | Identifier with business meaning |
| Identity column | GENERATED ... AS IDENTITY auto-number |
| Serial | Legacy auto-number type (sequence plus default) |
| UUIDv4 | 128-bit identifier with 122 random bits |
| UUIDv7 | UUID with a Unix-millisecond timestamp prefix, time-ordered |
| ULID | 26-character sortable identifier with a 48-bit timestamp |
| Composite key | A key of several columns |
| Foreign key | A column referencing a parent key |
ON DELETE / ON UPDATE | Referential action when a parent row is deleted or its key updated |
RESTRICT / NO ACTION | Refuse the parent change (RESTRICT cannot be deferred) |
CASCADE | Propagate the delete or update to children |
SET NULL / SET DEFAULT | Replace the child's key with NULL or its default |
| Deferrable constraint | Checked at commit instead of per statement |
CHECK constraint | A row-level boolean rule |
EXCLUDE constraint | No two rows may satisfy the operators together |
NOT NULL | The column cannot hold NULL |
| Three-valued logic | true, false and unknown |
NULLS NOT DISTINCT | Treat NULLs as equal in a unique constraint |
IS DISTINCT FROM | Null-safe inequality |
| Enum | A named set of values as a type |
| Lookup table | A small table of allowed values referenced by FK |
| Polymorphic association | Relationship whose target table is chosen by a type column |
| EAV | Entity-attribute-value rows instead of columns |
jsonb | Binary JSON type with indexing |
| GIN | Generalized inverted index, used for jsonb, arrays, full text |
| Array | A column holding a list of one type |
| Range type | One value representing an interval (tstzrange) |
| Multirange | An ordered set of non-overlapping ranges |
| Domain | A base type plus constraints with a name |
timestamptz | An instant, stored as UTC |
timestamp | A wall-clock reading with no zone |
AT TIME ZONE | Converts between instants and local readings |
interval | A duration stored as months, days and microseconds |
| DST | Daylight saving time |
numeric | Exact arbitrary-precision decimal |
money | Locale-dependent fixed-point currency type to avoid |
| Floating point | Approximate binary real/double precision |
text / varchar(n) / char(n) | Unlimited string / length-checked string / blank-padded string |
citext | Case-insensitive text extension |
| Collation | Rules for comparing and ordering strings |
utf8mb4 | MySQL's full 4-byte UTF-8 character set |
boolean | true, false or null |
inet / cidr | IP address / network types |
| Generated column | A column computed from others, STORED or VIRTUAL |
| Soft delete | Marking a row deleted instead of removing it |
| Audit columns | created_at, updated_at, created_by, deleted_at |
| Partitioning | Splitting a table by key into child tables |
| Tenant column | tenant_id scoping a row to a customer |
| Affinity (SQLite) | A column's type preference; values are not forced |
STRICT (SQLite) | Table option enforcing declared types |
DATETIME vs TIMESTAMP (MySQL) | No conversion and wide range vs UTC-converted and 2038 limit |
sql.NullString / sql.Null[T] | Go types that carry a Valid flag for NULL |
| Cast (Eloquent) | Conversion between a column and a PHP type |
| Migration | A versioned schema change script |
References
- E. F. Codd, "A Relational Model of Data for Large Shared Data Banks", CACM 13(6), June 1970. PDF mirror
- PostgreSQL manual: Numeric Types, Date/Time Types, Character Types, JSON Types, Arrays, Range Types, Network Address Types, UUID functions, Constraints, Generated Columns, CREATE DOMAIN, SET CONSTRAINTS, CREATE MATERIALIZED VIEW
- PostgreSQL wiki, Don't Do This
- SQLite: Datatypes In SQLite, STRICT Tables
- Laravel 13: Migrations, Eloquent, Attribute casting, Relationships, Query builder
- Go:
database/sql,math/big.Rat - MySQL type, character-set and FK behaviours on this page are from the MySQL Reference Manual (data types,
utf8mb4, foreign keys), which returned HTTP 403 to automated fetching; those statements were not re-read from a saved page. - Related: ID Generation at Scale, Indexing, Zero-Downtime Schema Migrations, Multi-Tenancy Strategies, Isolation Levels, Partitioning & Sharding in PostgreSQL