11. MySQL Part 2: UPDATE, ALTER, DELETE, Keys, Constraints and Users
11.6 Constraints: NOT NULL, DEFAULT, CHECK, AUTO_INCREMENT
Constraints (मर्यादा / नियम) mhanje database-level niyam – chukicha data table madhe yetach nahi, app madhe bug asla tari.
CREATE TABLE payments (
payment_id INT AUTO_INCREMENT PRIMARY KEY, -- 1, 2, 3 ... automatically
student_id INT NOT NULL, -- must have a value
amount DECIMAL(10,2) NOT NULL CHECK (amount > 0),
mode VARCHAR(10) NOT NULL DEFAULT 'UPI'
CHECK (mode IN ('UPI','Card','Cash','NetBanking')),
paid_on DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (student_id) REFERENCES students(student_id)
);
INSERT INTO payments (student_id, amount) VALUES (1, 5000); -- mode=UPI, paid_on=now
INSERT INTO payments (student_id, amount) VALUES (1, -10); -- rejected by CHECK
INSERT INTO payments (amount) VALUES (100); -- rejected: student_id NOT NULL
ALTER TABLE payments AUTO_INCREMENT = 1001; -- next id starts at 1001
| Constraint | Purpose |
|---|---|
NOT NULL |
Value is required |
DEFAULT |
Value used when none is given |
CHECK |
Value must satisfy a condition (enforced in MySQL 8.0.16+ and MariaDB 10.2+) |
AUTO_INCREMENT |
Automatic increasing number, usually for the primary key |
UNIQUE, PRIMARY KEY, FOREIGN KEY |
Covered in section 11.5 |
Why this matters for security
Constraints are a second line of defence for integrity: even if a bug or attacker bypasses application validation, the database refuses negative payments or orphan rows. Also note that sequential AUTO_INCREMENT ids are easy to guess – if an app shows /invoice.php?id=1001 without an ownership check, changing it to 1002 is an IDOR attack (Part 11).
Ravindra Bagale's Tip
Old MySQL (before 8.0.16) used to quietly ignore CHECK constraints – many students think the rule is in place, but bad data keeps coming in. Check the version with SELECT VERSION(); and insert one wrong row to test whether the rule really works.
Ravindra Bagale's Tip – मराठी
जुना MySQL (8.0.16 च्या आधी) CHECK constraint ला शांतपणे ignore करायचा – बऱ्याच students ना वाटतं नियम लागला, पण चुकीचा data येतच राहतो. SELECT VERSION(); ने version बघा आणि एक चुकीची row टाकून नियम खरंच चालतोय का ते test करा.
Ravindra Bagale's Tip – हिंदी
पुराना MySQL (8.0.16 से पहले) CHECK constraint को चुपचाप ignore कर देता था – बहुत से students को लगता है नियम लग गया, पर गलत data आता रहता है. SELECT VERSION(); से version देखो और एक गलत row डालकर test करो कि नियम सच में चल रहा है या नहीं.
Practice task
Create payments, insert two valid rows, and try three invalid ones (negative amount, invalid mode, missing student). Note the error for each.