List the kinds of constraints PostgreSQL supports and give an example of each in one CREATE TABLE.
Show the explanation
NOT NULL— a value is required.CHECK— a boolean condition each row must satisfy.UNIQUE— no two rows share the value(s).PRIMARY KEY— UNIQUE + NOT NULL; the row identity.FOREIGN KEY(REFERENCES) — the value must exist in another table, with an action on delete/update.EXCLUDE— a generalised uniqueness (e.g. no overlapping bookings), PostgreSQL-specific.DEFAULTis not strictly a constraint but is declared alongside them.
create table enrolments (
id bigint generated always as identity primary key,
student_id bigint not null references students(id) on delete cascade,
course_code text not null,
marks int check (marks between 0 and 100),
enrolled_on date not null default current_date,
unique (student_id, course_code)
);Constraints keep bad data out no matter which application writes to the database, which is why they are better than validation in application code alone. Name them (constraint marks_range check (...)) to get clearer error messages.
Original UniCircle question. Last reviewed 22 Oct 2026.
