Skill 1.1.4

Design and implement database constraints, including PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, and DEFAULT

Key Concepts

A PRIMARY KEY identifies each row, rejects duplicates and NULLs, and by default creates a clustered index; a table has one. A FOREIGN KEY requires that values exist in the referenced primary or unique key, and its ON DELETE and ON UPDATE actions (NO ACTION, CASCADE, SET NULL or SET DEFAULT) control what happens to child rows. Foreign key columns are not indexed automatically, so an index on them speeds up joins and parent deletes. A UNIQUE constraint enforces uniqueness on other candidate keys, such as an email address, and allows one NULL.

A CHECK constraint evaluates a Boolean expression for each row, for example CHECK (Quantity > 0) or a REGEXP_LIKE pattern for email formats; rows for which the expression is FALSE are rejected, while UNKNOWN (NULL) passes. A DEFAULT supplies a value when an INSERT omits the column, such as SYSUTCDATETIME() or NEXT VALUE FOR a sequence. Constraints added WITH NOCHECK skip existing rows and are marked untrusted, so the optimizer cannot rely on them.