Database Deadlocks, Part 1: The Patterns

Two correct transactions, locally fine in isolation, kill each other. The cycle forms in the global ordering across concurrent sessions, which no single query can see. The query in the error log isn't wrong; the lock it was waiting for isn't held by a misbehaving process. The bug is the interaction.

Joins That Lie: The Cardinality Problem

A query joins customers to orders to order_items, sums total_cents, and reports $4.2M for the quarter. Finance reports $3.0M from the billing system. The SQL is fine. The 1:N join to order_items duplicated every order total by the average items-per-order, and SUM dutifully added them all up.

Comment Your Schema

A column called `status TINYINT NOT NULL` in a table you've never seen. Is `1` active? Pending? Enabled? Is `0` deleted or just inactive? The column type doesn't tell you. Neither does the column name. The fix is one line of DDL nobody writes.

Foreign Keys Are Not Optional

An `INSERT INTO order_items (order_id) VALUES (9999)` against an order_id that doesn't exist. With a foreign key the database rejects the row. Without one, the row lands and the corruption surfaces months later when finance can't reconcile a report or backups have already rotated past the window.