Constraints in MySQL are rules that you apply to your tables to control what kind of data can be stored. They help maintain data accuracy, integrity, and reliability by preventing invalid entries.
1. NOT NULL
This ensures that a column must always have a value. You cannot leave it blank during data insertion.
Syntax:
CREATE TABLE table_name (
column_name datatype NOT NULL
);
Example:
CREATE TABLE students (
id INT NOT NULL,
name VARCHAR(100) NOT NULL
);
2. UNIQUE
Ensures that every value in a column is different from all others. Commonly used for emails or usernames.
Syntax:
CREATE TABLE table_name (
column_name datatype UNIQUE
);
Example:
CREATE TABLE users (
email VARCHAR(100) UNIQUE
);
3. PRIMARY KEY
Uniquely identifies each row in a table. It must always be unique and not null.
Syntax:
CREATE TABLE table_name (
column_name datatype PRIMARY KEY
);
Example:
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50)
);
4. FOREIGN KEY
Links one table to another — helps build relationships like parent-child tables.
Syntax:
CREATE TABLE child_table (
column_name datatype,
FOREIGN KEY (column_name) REFERENCES parent_table(parent_column)
);
Example:
CREATE TABLE orders (
order_id INT PRIMARY KEY,
user_id INT,
FOREIGN KEY (user_id) REFERENCES users(id)
);
5. DEFAULT
Assigns a default value to a column if none is provided during insertion.
Syntax:
CREATE TABLE table_name (
column_name datatype DEFAULT default_value
);
Example:
CREATE TABLE products (
name VARCHAR(100),
stock INT DEFAULT 0
);
6. CHECK
Ensures that values in a column meet a certain condition.
Syntax:
CREATE TABLE table_name (
column_name datatype CHECK (column_name condition)
);
Example:
CREATE TABLE accounts (
id INT,
balance INT CHECK (balance >= 0)
);
7. AUTO_INCREMENT
Automatically increases the value in a numeric column each time a new row is inserted, often used for IDs.
Syntax:
CREATE TABLE table_name (
column_name INT AUTO_INCREMENT PRIMARY KEY
);
Example:
CREATE TABLE tickets (
ticket_id INT AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(100)
);