Zum Inhalt springen
uencoder

SQL Constraint Referenz

Referenz für SQL constraints: primary Schlüssel, foreign Schlüssel, eindeutig, prüfen, nicht null, und 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
row identity
FOREIGN KEY
Referential integrity
links tables
CHECK
Boolean condition
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
mass deletion
SET NULL
Nullify FK
keep dependent
RESTRICT
Block deletion
default

Verwandte Tools

参考链接