Constraints

Basic SQL
≈ 1 min read

The database can enforce rules too

A constraint is a rule that the database checks when data changes. If a new value violates the rule, the database should not silently store an invalid row — the operation is rejected.

CREATE TABLE users (
    id INTEGER,
    email VARCHAR(200) NOT NULL UNIQUE,
    age INTEGER CHECK (age >= 0)
);

NOT NULL requires a value to be present, UNIQUE prevents duplicate values within the corresponding constraint, and CHECK verifies a specified logical condition.

Why important rules belong in the database

An application can validate data too, but the database is the final storage layer. If an important rule exists only in one piece of application code, another service, script, or incorrect command may bypass it. A constraint makes the rule part of the data schema itself.

Constraints protect data integrity, not all business logic. Simple, stable rules such as required values or valid ranges fit well in the database. More complex business scenarios usually remain in the application layer.