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
SQL
x
1
CREATE TABLE table_name (
2
column_name datatype constraint,
3
...
4
);
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 NULL
andUNIQUE
)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.
SQL
1
1
CREATE TABLE students_new (
2
student_id INT PRIMARY KEY,
3
full_name VARCHAR(100) NOT NULL,
4
email VARCHAR(100) UNIQUE,
5
birth_year INT CHECK (birth_year >= 1990),
6
enrollment_year INT DEFAULT 2023
7
);
