Chapter 13 — Key Takeaways
The big idea
DML changes data, so habits matter as much as syntax. Reading is safe; writing can corrupt or destroy. The professional reflex: preview the WHERE with a SELECT, wrap in a transaction, verify, then commit.
INSERT
- Name your columns:
INSERT INTO t (a, b) VALUES (...)— robust and readable. - Multi-row
INSERTandINSERT ... SELECTare efficient; omitted columns take their defaults. RETURNINGhands back modified rows (e.g., the generated id) — no second query.
UPDATE / DELETE
UPDATE t SET ... WHERE ...;DELETE FROM t WHERE ....UPDATE ... FROMupdates using another table.- ⚠️ No
WHERE= every row. The canonical disaster. (Case Study 1.) - They respect foreign keys (a restricting FK blocks an unsafe delete).
TRUNCATE vs DELETE
TRUNCATEempties a whole table fast (noWHERE), canRESTART IDENTITY, fires no row triggers. Use only when you want the whole table gone (staging/temp).DELETE ... WHEREfor selective removal.
UPSERT
INSERT ... ON CONFLICT (cols) DO UPDATE SET x = EXCLUDED.x— atomic insert-or-update.DO NOTHING= insert-if-absent.EXCLUDED= the row you tried to insert.- Fixes check-then-insert race conditions and makes loads idempotent (safe to re-run). (Case Study 2.)
Transactions = your undo button (Ch. 26 preview)
BEGIN; <change> SELECT ...verify...; COMMIT; -- or ROLLBACK to undo
- Wrap risky changes; verify before
COMMIT. - Consider
\set AUTOCOMMIT offin productionpsql.
The safe sequence (memorize)
- Run the
WHEREas aSELECT(check the row count). 2.BEGIN. 3. Run the change. 4. Verify with aSELECT. 5.COMMIT(orROLLBACK).
Defense in depth (Case Study 1)
Transactions + least-privilege access + reviewed migrations (not ad-hoc edits) + tested backups. Don't rely on "I'll be careful."
Performance (Ch. 23 & 31 preview)
Multi-row INSERT/COPY ≫ many single inserts. Indexes speed the WHERE but slow every write (they must be maintained). Batch huge UPDATE/DELETE on busy tables.
You can now…
- ☐
INSERT(single/multi/SELECT) and capture output withRETURNING. - ☐
UPDATE/DELETEsafely with a verifiedWHERE, inside a transaction. - ☐ Choose
DELETEvsTRUNCATE. - ☐ Write atomic, idempotent upserts with
ON CONFLICT. - ☐ Use
BEGIN/COMMIT/ROLLBACKas an undo button.
Looking ahead
Chapter 14 — Data Definition. CREATE/ALTER/DROP, PostgreSQL data types and constraints in depth, sequences, and schemas — building the well-constrained tables you've been modifying.
One sentence to carry forward: Before any
UPDATEorDELETE, run theWHEREas aSELECTand wrap the change in a transaction — that one habit prevents the most expensive mistakes in databases.