Constraints, the database as the last line of defence
NOT NULL, CHECK, UNIQUE, partial unique, deferrable, foreign keys with ON DELETE actions, and SperoTek's composite tenant foreign keys.
The concept
Application code has bugs, races and other callers (scripts, admin SQL, a future service). Constraints are rules the database enforces on every write, no matter who makes it.
CREATE TABLE rooms (
id UUID PRIMARY KEY,
hostel_id UUID NOT NULL REFERENCES hostels(id) ON DELETE CASCADE,
room_number VARCHAR(20) NOT NULL,
capacity SMALLINT NOT NULL CHECK (capacity > 0),
current_occupancy SMALLINT NOT NULL DEFAULT 0,
CHECK (current_occupancy <= capacity), -- table-level CHECK
UNIQUE (hostel_id, room_number) -- composite uniqueness
);
Foreign key ON DELETE actions
| Action | Meaning | Hostel example |
|---|---|---|
RESTRICT / NO ACTION |
Refuse to delete the parent while children exist | A student or room with bookings can’t be deleted |
CASCADE |
Delete the children too | Deleting a hostel deletes its rooms |
SET NULL |
Null out the FK | Deleting a manager keeps the booking, with approved_by set to null |
Partial unique indexes
These enforce “unique among rows matching a condition”:
-- a room can only have ONE active booking per student/period
CREATE UNIQUE INDEX idx_unique_active_room_booking
ON bookings (student_id, academic_year, semester)
WHERE status IN ('PENDING','APPROVED','CHECKED_IN');
A cancelled booking no longer blocks a new one.
Deferrable constraints
Normally a constraint is checked after each statement. DEFERRABLE INITIALLY DEFERRED delays the check until commit, which lets you temporarily violate it inside a transaction (e.g. renumbering lines).
In your projects
initial-schema.sql · index.sql · Booking.javaCHECK (capacity > 0),CHECK (current_occupancy <= capacity)andUNIQUE (hostel_id, room_number).- Partial unique indexes
idx_unique_active_room_bookingandidx_unique_waitlist_entry. @OnDelete(action = OnDeleteAction.RESTRICT / CASCADE / SET_NULL)mirrors the SQL in JPA.
initial-schema.sql · cart-schema.sqlprice NUMERIC(10,2) CHECK (price > 0.00), loyalty_points CHECK (loyalty_points >= 0), and cart_items UNIQUE (cart_id, product_id) with ON DELETE CASCADE. One row per product per cart means quantity is updated, not duplicated.
scripts/009-ledger.sqlThese are accounting invariants enforced in SQL:
CONSTRAINT ck_journal_line_one_sided
CHECK ((debit > 0 AND credit = 0) OR (credit > 0 AND debit = 0)),
UNIQUE (entry_id, line_number) DEFERRABLE INITIALLY DEFERRED,
-- tenant isolation at the DB level:
UNIQUE (company_id, id),
FOREIGN KEY (company_id, account_id) REFERENCES accounts (company_id, id)The composite FK is the clever part. A journal line in company A cannot point to an account in company B, even if the application has a bug, because the FK requires the (company_id, account_id) pair to exist together.
Alternatives / complements
- Exclusion constraints (Postgres): “no two bookings for the same room may overlap in time”:
EXCLUDE USING gist (room_id WITH =, tstzrange(start, end) WITH &&). This is a powerful upgrade for booking systems. - Triggers: for rules that CHECK can’t express (SperoTek’s immutability, covered later).
- Domain types:
CREATE DOMAIN money_amount AS NUMERIC(19,4) CHECK (VALUE >= 0).
Related concepts you must know
- Index your foreign keys. Postgres doesn’t do it automatically. Store’s schema has the comment “PostgreSQL does not automatically index foreign keys” and adds
idx_products_category_id. Without an index, deletes on the parent scan the child table, and joins are slow. - NULL semantics.
UNIQUEallows many NULLs (NULLS NOT DISTINCTchanges that in PG15+).CHECKpasses when the expression is NULL. - Constraint naming conventions:
pk_,fk_,uq_,ck_,idx_.