AI Hints
Home›PostgreSQL Tutorial›Creating Tables
PostgreSQL · Lesson 18 of 120

Constraints

Rules for your data.

⏱ 2 min read▶ Video at 14:59🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

A database should refuse bad data. An event with no title, minus five seats, or the same title twice. Constraints are rules that Postgres checks on every write.

  • No title?
  • Minus 5 seats?
  • Duplicates?

Rules in action

Not null requires a title. Unique stops duplicate titles. Check makes sure seats is positive. Then we try to break the check rule. Run it. Postgres refuses the bad row, and says which rule it broke.

query.sqlsql
CREATE TABLE events (
  event_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  title    text NOT NULL UNIQUE,
  seats    integer NOT NULL CHECK (seats > 0)
);

INSERT INTO events (title, seats) VALUES ('Poetry Night', 30);
INSERT INTO events (title, seats) VALUES ('Open Mic', -5);
Output
CREATE TABLE
INSERT 0 1
ERROR:  new row for relation "events" violates check constraint "events_seats_check"
DETAIL:  Failing row contains (2, Open Mic, -5).

Constraint types

Not null means a value is required. Unique means no duplicates. Primary key is both. Check runs any test you write. And foreign key links to another table, which is next.

ConstraintMeans
NOT NULLrequired
UNIQUEno duplicates
PRIMARY KEYunique + not null
CHECK (...)custom rule
REFERENCESmust exist elsewhere

Summary

Constraints make Postgres reject bad data, with clear errors. Next, foreign keys.

Key takeaways
  • NOT NULL
  • UNIQUE
  • CHECK
Next up: Foreign Keys — links between tables