Constraint (SQL)
A constraint is a rule that limits what data a table column can hold, keeping data valid and consistent. Common constraints include PRIMARY KEY, FOREIGN KEY, NOT NULL, UNIQUE, and CHECK.
SQL
Constraints are enforced by the database itself, so bad data is rejected before it can be stored. For example, NOT NULL forbids missing values, and CHECK can require an age to be positive.
Defining constraints when you create a table is a key part of designing a reliable database — they guarantee rules even if application code forgets to.
Syntax
CREATE TABLE table_name (
column datatype CONSTRAINT_TYPE
);Examples
SQL
CREATE TABLE users (
id INT PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
age INT CHECK (age >= 0)
);Output:
Table created with validation rules.