✏️ Explanatory Question

What are constraints in MySQL and what are their types?

👁 9 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Section 2: Data Types & Constraints

11

What are constraints in MySQL and what are their types?

Level: Basic — Constraints are the rules that keep your data valid and consistent.

A constraint is a rule applied to a column or table that restricts the type of data that can go into it. Constraints enforce data integrity and accuracy — if an operation violates a constraint, MySQL rejects it.

The Main Types of Constraints

  • NOT NULL: Ensures a column cannot store a NULL value.
  • UNIQUE: Ensures all values in a column are different.
  • PRIMARY KEY: Uniquely identifies each row (NOT NULL + UNIQUE combined).
  • FOREIGN KEY: Links a column to the primary key of another table.
  • CHECK: Ensures values meet a specific condition (enforced from MySQL 8.0.16+).
  • DEFAULT: Assigns a default value when none is provided.
  • AUTO_INCREMENT: Automatically generates a unique sequential number.
Important note: Before MySQL 8.0.16, the CHECK constraint was parsed but ignored. From 8.0.16 onward, it is fully enforced — a common interview "gotcha".

Constraint Quick Reference

Constraint Purpose NULL Allowed?
NOT NULL Forbids empty values No
UNIQUE No duplicate values Yes (one NULL)
PRIMARY KEY Unique row identifier No
FOREIGN KEY Links tables Yes
CHECK Condition-based rule Depends on condition
DEFAULT Fallback value N/A

Quick Example — All Constraints Together

CREATE TABLE employees (
    emp_id     INT AUTO_INCREMENT PRIMARY KEY,        -- PRIMARY KEY + AUTO_INCREMENT
    emp_name   VARCHAR(100) NOT NULL,                 -- NOT NULL
    email      VARCHAR(100) UNIQUE,                   -- UNIQUE
    age        INT CHECK (age >= 18),                 -- CHECK
    status     VARCHAR(10) DEFAULT 'Active',          -- DEFAULT
    dept_id    INT,
    FOREIGN KEY (dept_id) REFERENCES departments(dept_id) -- FOREIGN KEY
);
Interviewer tip: List the seven constraints, then mention that constraints can be applied at column level (inline) or table level (after all columns) — a detail that impresses interviewers.