Chapter 14 — Key Takeaways
The big idea
DDL (CREATE/ALTER/DROP) defines structure. CREATE TABLE turns the relational model (Ch. 3) into reality — and the types and constraints you choose are your data's contract. This is theme #1 at the keyboard: a good schema makes bad data impossible.
Types are correctness decisions
- Money →
numeric(p,s)(neverreal/double). Time →timestamptz. Text →text(not reflexivevarchar(255)). Flags →boolean. Flexible →jsonb. (Appendix D.) - The wrong type causes money drift, date chaos, and silent bugs.
Constraints make integrity automatic
NOT NULL · DEFAULT · UNIQUE · PRIMARY KEY (one per table; can be composite) · CHECK · FOREIGN KEY.
- Single-column rules → column constraints; multi-column rules → table constraints.
- Name constraints for clear errors.
- Referential actions: ON DELETE RESTRICT (default, blocks), CASCADE (deletes children — convenient but dangerous), SET NULL. Choose deliberately per relationship.
- Every omitted constraint is a future bug — and constraints are hard to add once data is dirty. (Case Study 1.)
Auto-generated keys
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY (prefer ALWAYS; serial is legacy). Backed by a sequence.
ALTER is powerful — and risky on live data
- Adding a nullable, no-default column is fast (metadata-only).
- Adding
NOT NULLwith no default to a populated table fails → safe pattern: add nullable/default → backfill (in batches) →SET NOT NULL. ALTERtakes anACCESS EXCLUSIVElock; row-rewriting/scanning alters hold it the whole time → can cause outages on hot tables. Use batches, low-traffic windows,lock_timeout,NOT VALID+VALIDATE, andCREATE INDEX CONCURRENTLY. (Case Study 2 → why migrations are a discipline, Ch. 22.)
DROP & schemas
- Removal hierarchy:
DELETE(some rows) →TRUNCATE(all rows) →DROP TABLE(the table).DROP ... CASCADEalso removes dependents — check\d+first. - A schema is a namespace (default
public);search_pathcontrols unqualified lookups (Ch. 2 mystery).
You can now…
- ☐ Write
CREATE TABLEwith correct types and all constraint kinds. - ☐ Define foreign keys with the right
ON DELETEactions. - ☐ Use
GENERATED ... AS IDENTITYfor keys. - ☐
ALTERsafely (and recognize lock-heavy changes). - ☐ Use
DROP,CASCADE, and schemas knowingly. - ☐ Build a fully-constrained schema for your project.
Looking ahead
Chapter 15 — Views, Materialized Views & Functions. Reusable SQL objects: views (name/hide complex queries, control access), materialized views (cache results), and user-defined functions/triggers (logic in the database).
One sentence to carry forward: The constraints and types you choose at
CREATE TABLEare your data's permanent contract — declare them generously, because a good schema makes bad data unrepresentable.