🧩 Types of SQL Constraints (With Examples)
1) NOT NULL
Ensures a column cannot have empty values.
CREATE TABLE students (
id INT,
name VARCHAR(100) NOT NULL
);
2) UNIQUE
Ensures all values in a column are distinct (no duplicates).
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
email VARCHAR(150) UNIQUE
);
3) PRIMARY KEY
Uniquely identifies each row in the table; automatically NOT NULL and UNIQUE.
CREATE TABLE products (
product_id INT PRIMARY KEY,
name VARCHAR(100),
price DECIMAL(10,2)
);
4) FOREIGN KEY
Maintains referential integrity by linking a column to the primary key of another table.
CREATE TABLE orders (
order_id INT PRIMARY KEY,
product_id INT,
FOREIGN KEY (product_id) REFERENCES products(product_id)
);
5) CHECK
Validates values against a condition or rule.
CREATE TABLE users (
user_id INT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
age INT CHECK (age >= 18)
);
6) DEFAULT
Assigns a default value to a column when no value is provided.
CREATE TABLE accounts (
acct_id INT PRIMARY KEY,
balance DECIMAL(10,2) DEFAULT 0.00,
status VARCHAR(20) DEFAULT 'active'
);