sql / intermediate
Snippet
Durchsetzung von Domänen- und Referenzintegrität durch Schema-Constraints
Schema-Constraints setzen Geschäftsregeln direkt in der Datenbank-Engine durch. CHECK-Constraints validieren Wertebereiche oder Optionen, während FOREIGN KEY-Constraints die referenzielle Integrität absichern.
snippet.sql
sql
1
2
3
4
5
6
7
8
9
10
CREATE TABLE account_transactions (transaction_id INTEGER PRIMARY KEY,account_id INTEGER NOT NULL,amount DECIMAL(12, 2) NOT NULL,transaction_type VARCHAR(10) NOT NULL,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,CONSTRAINT chk_positive_amount CHECK (amount > 0.00),CONSTRAINT chk_valid_type CHECK (transaction_type IN ('DEPOSIT', 'WITHDRAWAL')),CONSTRAINT fk_account FOREIGN KEY (account_id) REFERENCES accounts(account_id));
Erklärung
1
transaction_id INTEGER PRIMARY KEY,
Legt transaction_id als eindeutigen Identifikator und Primärschlüssel fest.
2
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
Weist der Spalte den aktuellen Systemzeitstempel als Standardwert zu.
3
CONSTRAINT chk_positive_amount CHECK (amount > 0.00),
Verhindert das Einfügen negativer oder ungültiger Transaktionsbeträge.
4
CONSTRAINT chk_valid_type CHECK (transaction_type IN ('DEPOSIT', 'WITHDRAWAL')),
Beschränkt die zulässigen Zeichenkettenwerte für Transaktionstypen.
5
CONSTRAINT fk_account FOREIGN KEY (account_id) REFERENCES accounts(account_id)
Stellt sicher, dass account_id in der referenzierten Tabelle accounts existiert.