Constraint
In one line
A constraint is a rule enforced by the database — it rejects any data that violates the rule.
In simple words
Constraints are rules you define on table columns that the database enforces automatically. If you try to insert or update data that violates a constraint, the database rejects the operation with an error.
Common constraints:
- NOT NULL: the column must have a value.
- UNIQUE: no two rows can have the same value.
- PRIMARY KEY: a unique, not-null identifier for each row.
- FOREIGN KEY: the value must reference an existing row in another table.
- CHECK: the value must satisfy a custom condition.
- DEFAULT: a value used if none is provided.
Constraints are the database's way of protecting data integrity. They are checked on every INSERT, UPDATE, and (for foreign keys) DELETE. Defining good constraints is a key part of database design.
Example
sql
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
price NUMERIC(10,2) CHECK (price > 0),
sku TEXT UNIQUE NOT NULL,
cat_id INTEGER REFERENCES categories(id)
);Five constraints: PRIMARY KEY, NOT NULL, CHECK (price > 0), UNIQUE, and FOREIGN KEY.
Related terms
Related Resources
Related Lessons
- Constraints
Learn all constraint types.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.