Constraints & Keys

Constraints are rules attached to a column that the database enforces automatically, rejecting any change that would break them. They're what keeps bad data from ever making it into your tables in the first place.

NOT NULL and UNIQUE

NOT NULL requires a value in that column for every row. UNIQUE requires every value in that column to be different from every other:

create a users table with constraints
Result

Try changing the inserted row to reuse the same email in a second INSERT — the database will reject it rather than silently allowing a duplicate.

CHECK

CHECK enforces a condition on every row, beyond just "has a value" or "is unique" — for example, that a salary can never be negative:

a CHECK constraint
Result

FOREIGN KEY

A FOREIGN KEY links a column in one table to a column in another, and (when enforced) stops you from referencing a row that doesn't exist — this is how the database itself guarantees that every employee's department is a real department:

linking employees to departments
Result
Note: foreign key enforcement is off by default in SQLite (it has to be turned on with a separate setting), so this example will run even with a department that doesn't exist — in MySQL or Postgres, that insert would be rejected by default.