🔍
👶 Kids📝 Blog About Contact 🚀 Get Started Free

SQL – Constraints

Protect data integrity using SQL constraints — rules enforced at the database level on table columns.

Constraints are rules defined on a column (or table) that the database enforces automatically. They ensure data integrity — preventing invalid, inconsistent, or nonsensical data from ever entering the database. Rather than relying on your application code to validate every input, constraints build that validation directly into the database schema.

The main constraints are: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT. Each plays a distinct protective role.

Constraint overview

ConstraintProtection it provides
NOT NULLValue cannot be empty
UNIQUENo two rows can have the same value
PRIMARY KEYUnique + not null identifier
FOREIGN KEYMust match a value in another table
CHECKMust satisfy a custom condition
DEFAULTProvides a fallback value

Try It Yourself — Interactive SQL Editor

Edit the query below and click Run Query ▶ to see live results powered by SQLite running directly in your browser.

SQLite – edit & run
Results
← Click Run Query ▶ to see results

Key Points

  • Constraints are enforced by the DB engine — more reliable than app-level validation
  • Multiple constraints can be applied to a single column
  • Violations raise an error and prevent the INSERT/UPDATE
  • Constraints make schema self-documenting — readers see the rules immediately

Pro Tip from CodesCompiler: The best way to learn SQL is to break things intentionally — modify the query above, change the WHERE conditions, try different columns. Every error teaches you something the docs cannot.

In the next lesson, we continue exploring SQL’s powerful feature set to build your database mastery.