Ravindra BagaleCourses & study guides

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

Juna MySQL (8.0.16 chya aadhi) CHECK constraint la shantpane ignore karaycha – khup students la vatte niyam lagla, pan data yetach rahto. SELECT VERSION(); ne version bagha aani ek chukichi row takun niyam kharach chaltoy ka te test kara.

Practice task

Create payments, insert two valid rows, and try three invalid ones (negative amount, invalid mode, missing student). Note the error for each.