SQL Constraints

NOT NULL, UNIQUE, CHECK and DEFAULT.

✍️ 3 exercises + code challenge in this lesson

Constraints are rules that keep data valid. The database rejects any change that breaks them.

  • NOT NULL: the column must have a value.
  • UNIQUE: all values must be different.
  • PRIMARY KEY: uniquely identifies each row (NOT NULL + UNIQUE).
  • FOREIGN KEY: must match a key in another table.
  • CHECK: values must satisfy a condition.
  • DEFAULT: the value used when none is given.

Key Takeaways: SQL Constraints

Mastering SQL Constraints helps you write clean and reliable SQL code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

SQL Constraints Code Example

SQL
CREATE TABLE Accounts (
  AccountID INTEGER PRIMARY KEY,
  Username  TEXT NOT NULL UNIQUE,
  Age       INTEGER CHECK (Age >= 18),
  Status    TEXT DEFAULT 'active'
);

INSERT INTO Accounts (Username, Age) VALUES ('ali', 25);
SELECT * FROM Accounts;

-- This breaks the CHECK constraint, so it fails:
INSERT INTO Accounts (Username, Age) VALUES ('kid', 12);
Free sign-in required · Google login available

SQL Constraints Practice Exercises

Check what you learned in “SQL Constraints”.

/ 3 solved
Fill in the blank

Every username must be different.

Username TEXT NOT NULL 
✓ Correct! Not quite. Try again.
Multiple choice

Which constraint gives a column a value when none is provided?

✓ Correct! Not quite. Try again.
Code challenge

Create table Members (ID INTEGER PRIMARY KEY, Status TEXT DEFAULT 'active'), insert a row with only ID 1, then select Status.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services