What are primary keys, foreign keys and constraints?
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn What are primary keys, foreign keys and constraints?
Definition:
Keys identify records and relationships, while constraints tell the database which stored states are allowed. A primary key identifies each row, a foreign key validates a relationship, and other constraints enforce required or unique values and conditions. Database enforcement protects data even when different application paths write concurrently.
Key points:
-
Primary key: unique, non-NULL row identity.
-
Foreign key: ensures a referenced record exists.
-
NOT NULL,UNIQUEandCHECKenforce required values and data rules. -
A foreign key does not automatically choose the right delete behavior; decide whether related rows should restrict, cascade or become NULL.
Interview point:
- Application validation improves messages, while database constraints protect the rule across all writers.
Adapted from 05_SQL_POSTGRESQL.md · “What are primary keys, foreign keys and constraints?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.