← Database & SQL
MODULE 05 · DATABASE & SQL

Constraint

A database rule that limits what data can be stored so it stays valid and consistent.

01 · What is it?

A constraint is a database rule that limits what data can be stored so it stays valid and consistent.

The database checks the rule when data is added or changed. If the data breaks the rule, the database rejects the operation.

Simple Definition: A constraint is a guardrail for database data.

02 · Think of it like…

Think of a constraint like a rule at the entrance to a well-organized building. Only information that follows the rule is allowed inside.

Incoming dataNew value
ConstraintCheck the rule
DatabaseValid data only

03 · What does it do?

A constraint protects the data by checking rules such as:

Required values

A required field cannot be left empty.

Unique values

A value such as an email address cannot repeat.

Valid relationships

A reference must point to a real related record.

Allowed values

A value must fit an expected range or set.

04 · Where is it used?

Constraints are defined on database tables and are checked during inserts and updates.

Table definition

Rules can be declared when a table is created.

Data changes

Rules run when rows are inserted or updated.

Application safety

Rules protect the data even when several applications write to it.

05 · Example

Protecting a users table

CREATE TABLE users (
  id INTEGER PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  age INTEGER CHECK (age >= 13)
);

INSERT INTO users (id, email, age)
VALUES (1, 'sam@example.com', 12);

The insert is rejected because the CHECK constraint requires the age to be at least 13.

06 · How it connects

1Application input
2Backend validation
3SQL write
4Constraint check
5Success or error

Application validation improves the user experience; database constraints protect the stored data at the final boundary.

07 · Do Not Confuse

Constraint

A database rule that the stored data must obey.

Validation

A check often performed in application code before data reaches the database.

Index

A structure that helps find data faster; it is not mainly a validity rule.

09 · What to Remember

A constraint keeps invalid data out of the database.

Constraints protect required fields, unique values, relationships, and other data rules.

Application checks help users; database constraints protect the final stored state.

Data+Rule→Valid database state
↑