BE2: Data that stays correct

Lesson 2 of 5 ยท reading 15โ€“25 minutes; practice and project time is on the module page

Constraints: rules the database enforces

๐ŸŽฏYou'll be able to

Write constraints that keep bad data out even when application code has a bug.

๐Ÿ The everyday picture

A railway reservation chart has numbered berths. However busy the counter is, the chart can't hold two names on berth 23. The rule lives in the chart, not in the clerk's memory.

๐Ÿ“˜What it really is

๐Ÿ“A worked example

TiffinBox sells a limited number of tiffins per kitchen each day. A table and constraint:

CREATE TABLE daily_capacity (
  kitchen_id int REFERENCES kitchens(id),
  day        date,
  capacity   int NOT NULL CHECK (capacity >= 0),
  booked     int NOT NULL DEFAULT 0,
  PRIMARY KEY (kitchen_id, day),
  CHECK (booked <= capacity)
);

Input: kitchen 4 has capacity 50 and booked 50; an order runs UPDATE daily_capacity SET booked = booked + 1 WHERE kitchen_id = 4 AND day = '2026-11-02';. Expected output: an error from the check booked <= capacity. The handler turns it into 409 Conflict: Kitchen 4 is full for 2 November.

๐ŸŒWhere it's used

๐Ÿ“Case scenario

A support engineer runs a quick SQL fix to correct a customer's order and types qty = -2. The app's validation never ran, and the monthly report shows negative sales. A CHECK (qty BETWEEN 1 AND 20) would have rejected the fix at once, with an error the engineer could act on.

๐Ÿ–ฑ๏ธTry it

In psql, try three inserts that break the kit's constraints: a 0 quantity, a negative price and a duplicate customer sub. Then add the daily_capacity table above and try to overbook. Success: four clear errors, each naming its constraint.

โš ๏ธCommon mistakes

๐Ÿ› ๏ธFor your project

Project 1's idempotency relies on the request_keys primary key; Project 3's repeat-safety relies on processed_messages.

โœ…Quick check

Why add a constraint when the code already validates the value?

Show the answer

Because data can also arrive from scripts, imports, other services or future code that skips the check.

What should an API return when a unique constraint rejects a duplicate?

Show the answer

A 4xx, usually 409 Conflict, or the earlier result for an idempotent repeat, not a 500.

โ† PreviousTables, keys and relationships
ProLearners Assist