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.
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 differentPRIMARY KEY– Uniquely identifies each row (auto appliesNOT NULLandUNIQUE)FOREIGN KEY– Links records between tables (enforces referential integrity)CHECK– Sets a condition that values must meetDEFAULT– 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
);


