SQL Constraint Reference
Reference 为 SQL constraints: 主键, foreign 键, 唯一, 检查, 不空, 和 exclusion.
Constraint Types
PRIMARY KEY uniquely identifies rows and implies NOT NULL + UNIQUE. FOREIGN KEY enforces referential integrity to another table. UNIQUE prevents duplicate values (allows multiple NULLs in most DBs). CHECK enforces arbitrary boolean conditions. NOT NULL prevents null values. DEFAULT provides values when not specified. EXCLUSION (PostgreSQL) prevents overlapping ranges. Constraints can be column-level or table-level. DEFERRABLE constraints check at commit time, not per statement.
- PRIMARY KEY
- Unique + not null
- FOREIGN KEY
- Referential integrity
- CHECK
- Boolean condition
row identity links tables domain constraint Referential Integrity Actions
ON DELETE CASCADE removes dependent rows when parent is deleted. ON DELETE SET NULL nullifies foreign keys. ON DELETE RESTRICT prevents deletion if dependents exist (default). ON DELETE NO ACTION similar to RESTRICT (deferrable). ON UPDATE actions handle parent key changes. Cascading deletes can be dangerous (mass deletion). SET DEFAULT sets to the default value. Circular foreign keys require deferrable constraints or careful ordering. Always index foreign key columns for performance. Validate data before adding constraints to existing tables.
- CASCADE
- Delete dependents
- SET NULL
- Nullify FK
- RESTRICT
- Block deletion
mass deletion keep dependent default