SQL Constraints

SQL constraints are rules applied to table columns to ensure the accuracy, validity, and integrity of the data. Constraints are declared either during table creation or later using ALTER TABLE.

Tutorials dojo strip

SQL Constraints Syntax

CREATE TABLE table_name (
    column_name datatype constraint,
    ...
);

Common SQL Constraints

  • NOT NULL – Column must have a value (no empty entries)
  • UNIQUE – All values in the column must be different
  • PRIMARY KEY – Uniquely identifies each row (auto applies NOT NULL and UNIQUE)
  • FOREIGN KEY – Links records between tables (enforces referential integrity)
  • CHECK – Sets a condition that values must meet
  • DEFAULT – Assigns a default value if none is provided

SQL Constraints Example

This query defines several constraints on different columns.

CREATE TABLE students_new (
    student_id INT PRIMARY KEY,
    full_name VARCHAR(100) NOT NULL,
    email VARCHAR(100) UNIQUE,
    birth_year INT CHECK (birth_year >= 1990),
    enrollment_year INT DEFAULT 2023
);

SQL Constraints Labs

Tutorials dojo strip
Scroll to Top