Loading Depth Study
Preparing your workspace
Constraints enforce rules that keep database records valid, unique, and correctly related.
PostgreSQL supports primary keys, foreign keys, unique constraints, not-null constraints, check constraints, and defaults. A primary key identifies a row. A foreign key creates a relationship to another table. Unique constraints prevent duplicates, while check constraints enforce business-level conditions that can be represented at the database layer. Constraints help ensure that invalid data cannot silently enter the system.
An enrollment can require a valid student ID and course ID, while a user email can be required to remain unique.
CREATE TABLE enrollments ( id UUID PRIMARY KEY, student_id UUID NOT NULL, course_id UUID NOT NULL, score NUMERIC(5,2) CHECK (score >= 0 AND score <= 100), FOREIGN KEY (student_id) REFERENCES students(id), FOREIGN KEY (course_id) REFERENCES courses(id) );
The enrollment table enforces valid relationships and keeps score values between 0 and 100.