Loading Depth Study
Preparing your workspace
Constraints are database rules that protect data integrity, while keys identify records and relationships.
A primary key uniquely identifies each row in a table. A foreign key connects a column to a primary key in another table. UNIQUE prevents duplicate values, NOT NULL requires a value, DEFAULT provides a value when one is not supplied, and CHECK can enforce conditions where supported by the database configuration. These constraints move important data rules into the database instead of relying only on application code.
An enrollments table can contain student_id and course_id as foreign keys pointing to students and courses.
CREATE TABLE enrollments ( id INT PRIMARY KEY AUTO_INCREMENT, student_id INT NOT NULL, course_id INT NOT NULL, enrolled_at DATETIME NOT NULL, FOREIGN KEY (student_id) REFERENCES students(id), FOREIGN KEY (course_id) REFERENCES courses(id) );
The enrollments table links students and courses using foreign keys.