Module 52: Database Structure

Lesson 4 of 5 · 15–25 minutes

Constraints

🏠The everyday picture

A ticket machine that refuses torn notes, won't sell a seat that's already sold, and won't print a ticket without a date. The rules are built into the machine, so no clerk can forget them.

📘What it really is

Constraints are rules the database enforces on every change, from every program, forever:

amount_paise integer NOT NULL CHECK (amount_paise > 0),
status text NOT NULL CHECK (status IN ('new', 'in-progress', 'closed'))

Why constraints matter even when your API validates (Module 43):

Validate in the API for friendly messages, and constrain in the database for guarantees.

🖱️Try it

Add constraints to your tables: names required, emails unique, payment amounts positive, method limited to 'cash', 'upi' and 'card', created_at defaulting to the current time. Try to break each rule with an INSERT and read the error message.

✅Quick check

The API already validates payment amounts. Why add a CHECK constraint too?

Show the answer

Other programs or bugs could still write bad data; the database guarantees the rule for every write.

What does DEFAULT now() do on a created_at column?

Show the answer

Fills in the current time automatically when a row is inserted without a value.

← PreviousPrimary keys
ProLearners Assist