Academic Block

SQL CONSTRAINTS Get Certified

Learn how constraints enforce rules on table data, protecting accuracy, consistency and referential integrity.

What are SQL Constraints?

Constraints are rules attached to columns or tables that the database engine automatically enforces. They reject any INSERT or UPDATE that would violate the rule, keeping the data clean and reliable.

The most common constraints are:

  • NOT NULL
  • UNIQUE
  • PRIMARY KEY
  • FOREIGN KEY
  • CHECK
  • DEFAULT

NOT NULL

Prevents a column from ever containing a NULL value. Use it for information that every row must have.

What this code does: Creates a students table where both name and course are mandatory.

DROP TABLE IF EXISTS students;
CREATE TABLE students (
  student_id INTEGER PRIMARY KEY,
  student_name TEXT NOT NULL,
  course TEXT NOT NULL
);
INSERT INTO students (student_name, course) VALUES
  ('Aarav', 'Physics'),
  ('Meera', 'Computer Science'),
  ('Kabir', 'Mathematics');
SELECT *
FROM students
ORDER BY student_id;

UNIQUE

Guarantees that no two rows share the same value in the constrained column(s). Ideal for emails, usernames, codes, etc.

What this code does: Ensures every customer email address is unique.

DROP TABLE IF EXISTS customers;
CREATE TABLE customers (
  customer_id INTEGER PRIMARY KEY,
  customer_name TEXT NOT NULL,
  email TEXT UNIQUE
);
INSERT INTO customers (customer_name, email) VALUES
  ('Riya', 'riya@example.com'),
  ('Arjun', 'arjun@example.com'),
  ('Nisha', 'nisha@example.com');
SELECT *
FROM customers
ORDER BY customer_id;

PRIMARY KEY

A primary key uniquely identifies each row. It is automatically UNIQUE and NOT NULL. In SQLite an INTEGER PRIMARY KEY also acts as an auto-incrementing identifier when no value is supplied.

What this code does: Creates a products table whose primary key uniquely identifies every product.

DROP TABLE IF EXISTS products;
CREATE TABLE products (
  product_id INTEGER PRIMARY KEY,
  product_name TEXT NOT NULL,
  price REAL
);
INSERT INTO products (product_id, product_name, price) VALUES
  (101, 'Wireless Mouse', 799.00),
  (102, 'USB Hub', 599.00),
  (103, 'Laptop Stand', 1499.00);
SELECT *
FROM products
ORDER BY product_id;

FOREIGN KEY

Links a column in one table to the primary key of another table, enforcing referential integrity. In SQLite you must enable the feature with PRAGMA foreign_keys = ON.

What this code does: Creates customers and orders tables related by a foreign key and joins them.

PRAGMA foreign_keys = ON;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS customers;
CREATE TABLE customers (
  customer_id INTEGER PRIMARY KEY,
  customer_name TEXT NOT NULL
);
CREATE TABLE orders (
  order_id INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL,
  product_name TEXT NOT NULL,
  FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
INSERT INTO customers VALUES
  (1, 'Aarav'),
  (2, 'Meera'),
  (3, 'Kabir');
INSERT INTO orders VALUES
  (101, 1, 'Keyboard'),
  (102, 2, 'Monitor'),
  (103, 1, 'Mouse');
SELECT
  orders.order_id,
  customers.customer_name,
  orders.product_name
FROM orders
JOIN customers
  ON orders.customer_id = customers.customer_id
ORDER BY orders.order_id;

CHECK

Rejects any value that does not satisfy a Boolean expression. Useful for ranges, positive numbers, allowed lists, etc.

What this code does: Ensures age is at least 18 and salary is greater than zero.

DROP TABLE IF EXISTS employees;
CREATE TABLE employees (
  employee_id INTEGER PRIMARY KEY,
  employee_name TEXT NOT NULL,
  age INTEGER CHECK (age >= 18),
  salary REAL CHECK (salary > 0)
);
INSERT INTO employees (employee_name, age, salary) VALUES
  ('Neha', 28, 52000),
  ('Vikram', 34, 68000),
  ('Sana', 25, 47000);
SELECT *
FROM employees
ORDER BY employee_id;

DEFAULT

Supplies a value automatically when an INSERT statement does not provide one for that column.

What this code does: New tasks receive the status “Pending” unless another value is given.

DROP TABLE IF EXISTS tasks;
CREATE TABLE tasks (
  task_id INTEGER PRIMARY KEY,
  task_name TEXT NOT NULL,
  status TEXT DEFAULT 'Pending'
);
INSERT INTO tasks (task_name) VALUES
  ('Design homepage'),
  ('Test login form'),
  ('Update documentation');
SELECT *
FROM tasks
ORDER BY task_id;

Multiple Constraints Together

A single table (or even a single column) can carry several constraints at once.

What this code does: Creates a courses table that combines PRIMARY KEY, NOT NULL, UNIQUE, CHECK and DEFAULT.

DROP TABLE IF EXISTS courses;
CREATE TABLE courses (
  course_id INTEGER PRIMARY KEY,
  course_code TEXT NOT NULL UNIQUE,
  course_name TEXT NOT NULL,
  duration_months INTEGER CHECK (duration_months > 0),
  status TEXT DEFAULT 'Active'
);
INSERT INTO courses (course_code, course_name, duration_months) VALUES
  ('PHY101', 'Applied Physics', 6),
  ('DES201', 'Product Design', 8),
  ('ROB301', 'Robotics Engineering', 12);
SELECT *
FROM courses
ORDER BY course_id;

Column-Level vs Table-Level Constraints

Constraints written next to a column definition are column-level. Constraints written after all columns (and that may involve more than one column) are table-level.

What this code does: Uses a composite UNIQUE constraint and a table-level CHECK on the score range.

DROP TABLE IF EXISTS enrollments;
CREATE TABLE enrollments (
  enrollment_id INTEGER PRIMARY KEY,
  student_name TEXT NOT NULL,
  course_name TEXT NOT NULL,
  score INTEGER,
  UNIQUE (student_name, course_name),
  CHECK (score BETWEEN 0 AND 100)
);
INSERT INTO enrollments (student_name, course_name, score) VALUES
  ('Aarav', 'Physics', 88),
  ('Meera', 'Mathematics', 94),
  ('Kabir', 'Chemistry', 81);
SELECT *
FROM enrollments
ORDER BY enrollment_id;

Putting Constraints Together for Real Integrity

What this code does: Combines PRIMARY KEY, NOT NULL, UNIQUE, CHECK, DEFAULT and FOREIGN KEY in a realistic workshops / registrations schema.

PRAGMA foreign_keys = ON;
DROP TABLE IF EXISTS registrations;
DROP TABLE IF EXISTS workshops;
CREATE TABLE workshops (
  workshop_id INTEGER PRIMARY KEY,
  workshop_name TEXT NOT NULL,
  seats INTEGER CHECK (seats > 0)
);
CREATE TABLE registrations (
  registration_id INTEGER PRIMARY KEY,
  workshop_id INTEGER NOT NULL,
  participant_email TEXT NOT NULL UNIQUE,
  status TEXT DEFAULT 'Confirmed',
  FOREIGN KEY (workshop_id) REFERENCES workshops(workshop_id)
);
INSERT INTO workshops VALUES
  (1, 'Robotics Lab', 20),
  (2, 'CAD Workshop', 15);
INSERT INTO registrations (workshop_id, participant_email) VALUES
  (1, 'student1@example.com'),
  (2, 'student2@example.com');
SELECT
  registrations.registration_id,
  workshops.workshop_name,
  registrations.participant_email,
  registrations.status
FROM registrations
JOIN workshops
  ON registrations.workshop_id = workshops.workshop_id
ORDER BY registrations.registration_id;

Common SQL Constraints

Constraint
Purpose
Example
NOT NULL
Prevents NULL values
name TEXT NOT NULL
UNIQUE
Prevents duplicate values
email TEXT UNIQUE
PRIMARY KEY
Uniquely identifies each row
id INTEGER PRIMARY KEY
FOREIGN KEY
Links related tables
FOREIGN KEY (customer_id) REFERENCES customers(id)
CHECK
Requires a condition to be true
age INTEGER CHECK (age >= 18)
DEFAULT
Provides a value when none is given
status TEXT DEFAULT ‘Active’

Important Points

  • Constraints are enforced automatically by the database engine.
  • NOT NULL and UNIQUE protect individual columns.
  • PRIMARY KEY combines uniqueness and non-nullability.
  • FOREIGN KEY maintains relationships between tables (enable with PRAGMA in SQLite).
  • CHECK and DEFAULT give fine-grained control over allowed values.
  • Multiple constraints can be combined on the same column or table.

Best Practices

  • Always define a primary key for tables that represent distinct entities.
  • Use NOT NULL for every column whose value is mandatory.
  • Add UNIQUE constraints to columns that must not contain duplicates.
  • Apply CHECK constraints for ranges, positive numbers or enumerated sets.
  • Use FOREIGN KEY relationships to keep related tables consistent.
  • Choose sensible DEFAULT values for optional columns.
  • Design all constraints before loading large volumes of data.

SQL CONSTRAINTS are the database’s first line of defence against bad data. Applied thoughtfully they make tables reliable, consistent and far easier to maintain. Click Test My Code on any example to run it live, or Code Explanation to walk through the query block by block.

Ctrl + Enter to run code in the editor Esc to close the editor

🧪 Test Your SQL Code

Edit the SQL code on the left and click “Run Code” to see the result on the right.

📝 SQL Code
👁️ Preview (query result)

Click “Run Code” to see the result here.