🧩 Types of SQL Constraints (With Examples)
1) NOT NULL
The NOT NULL constraint ensures that a column cannot store empty or missing values, making it essential for fields where data must always be provided.
CREATE TABLE students (
id INT,
name VARCHAR(100) NOT NULL
);
2) UNIQUE
The UNIQUE constraint ensures that all values in a column are distinct. It prevents duplicate entries and is commonly used for fields like email or username.
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
email VARCHAR(150) UNIQUE
);
3) PRIMARY KEY
A PRIMARY KEY uniquely identifies each row in a table. It automatically applies both NOT NULL and UNIQUE, making it one of the most important constraints in SQL.
CREATE TABLE products (
product_id INT PRIMARY KEY,
name VARCHAR(100),
price DECIMAL(10,2)
);
4) FOREIGN KEY
A FOREIGN KEY constraint maintains referential integrity by linking a column in one table to the PRIMARY KEY of another table. It ensures valid relationships between tables.
CREATE TABLE orders (
order_id INT PRIMARY KEY,
product_id INT,
FOREIGN KEY (product_id) REFERENCES products(product_id)
);
5) CHECK
The CHECK constraint validates data based on a specific condition. It ensures that only values meeting the rule are allowed—for example, age must be 18 or above.
CREATE TABLE users (
user_id INT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
age INT CHECK (age >= 18)
);
6) DEFAULT
The DEFAULT constraint automatically assigns a value to a column when no value is provided. It is useful for setting standard values such as account status or initial balance.
CREATE TABLE accounts (
acct_id INT PRIMARY KEY,
balance DECIMAL(10,2) DEFAULT 0.00,
status VARCHAR(20) DEFAULT 'active'
);
