Constraints enforce data integrity.
Constraint Types
PRIMARY KEY� unique identifierFOREIGN KEY� references another tableNOT NULL� cannot be NULLUNIQUE� no duplicatesDEFAULT� default valueCHECK� validation rule
Constraints enforce data integrity.
PRIMARY KEY � unique identifierFOREIGN KEY � references another tableNOT NULL � cannot be NULLUNIQUE � no duplicatesDEFAULT � default valueCHECK � validation ruleCREATE TABLE orders ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, total DECIMAL(10,2) CHECK (total >= 0), status VARCHAR(20) DEFAULT "pending", FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE );
CREATE TABLE orders ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, code VARCHAR(20) UNIQUE, total DECIMAL(10,2) CHECK (total >= 0), status ENUM("pending", "paid", "shipped") DEFAULT "pending", created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ); -- Add a UNIQUE constraint ALTER TABLE users ADD CONSTRAINT uc_email UNIQUE (email); -- Add a CHECK constraint (MySQL 8.0.16+) ALTER TABLE products ADD CONSTRAINT chk_price CHECK (price > 0); -- Remove constraint ALTER TABLE users DROP INDEX uc_email;
Create a table with PRIMARY KEY, UNIQUE, and FOREIGN KEY.
CREATE TABLE reviews (
id INT AUTO_INCREMENT PRIMARY KEY,
product_id INT NOT NULL,
rating INT CHECK (rating BETWEEN 1 AND 5),
FOREIGN KEY (product_id) REFERENCES products(id)
);
ON DELETE CASCADE does what?
Automatically deletes child rows when parent is deleted.
Both enforce uniqueness. PRIMARY KEY cannot be NULL and only one per table. UNIQUE allows NULLs and multiple per table.