Constraints

A constraint is a rule the database enforces, so bad data cannot get in even by accident.

NOT NULL, UNIQUE, PRIMARY KEY, REFERENCES, CHECK, DEFAULT.

Validation in your application produces a helpful error message. The constraint is what makes the rule true, regardless of which application, script, migration or person is writing at the time.

Try it

Which of the three errors would be hardest to diagnose if the constraint did not exist and the bad row simply went in?

loading editor…
real SQLite, in your browser

Each of those three violates a different constraint. Uncomment one at a time and read what SQLite says.

✦ SQLite does not enforce foreign keys by default

It parses REFERENCES and then, unless you run PRAGMA foreign_keys = ON, does not check it. That surprises people moving from SQLite to PostgreSQL, where a foreign key that was quietly ignored in development suddenly rejects data in production.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back