Skip to content
Codewilds

Lesson 23 of 30 · Designing Tables

SQL Constraints: NOT NULL, UNIQUE, DEFAULT and CHECK

medium20 XP3 min read

A table with types is a good start, but it still accepts nonsense: a bounty without a target, two bounties on the same target, a reward of −5 gold. Constraints are rules you attach to columns. The database checks them on every INSERT and UPDATE and rejects any row that breaks one.

Four column constraints

CREATE TABLE bounties (
  id INTEGER PRIMARY KEY,
  target TEXT NOT NULL UNIQUE,
  reward INTEGER NOT NULL CHECK (reward > 0),
  status TEXT NOT NULL DEFAULT 'open'
);
  • NOT NULL: the column must have a value. INSERT INTO bounties (reward) VALUES (100); fails with NOT NULL constraint failed: bounties.target.
  • UNIQUE: no two rows may share a value. A second bounty on 'Grey Wolf' fails with UNIQUE constraint failed: bounties.target.
  • DEFAULT value: used when an INSERT leaves the column out. A new bounty starts with status 'open', the same way purchases.quantity gets its 1.
  • CHECK (condition): any condition on the row. A reward of −5 fails with CHECK constraint failed: reward > 0. Other examples: CHECK (level BETWEEN 1 AND 100), CHECK (status IN ('open', 'claimed')).

Constraints follow the column's type, in any order, and you can combine as many as you need.

INSERT INTO bounties (target, reward) VALUES ('Grey Wolf', 80);
SELECT * FROM bounties;   -- 1 | Grey Wolf | 80 | open

Rules for several columns

Some rules involve more than one column. Write them as table constraints after the last column:

CREATE TABLE season_scores (
  hero_id INTEGER NOT NULL,
  season INTEGER NOT NULL,
  points INTEGER NOT NULL DEFAULT 0,
  UNIQUE (hero_id, season)
);

A hero can have scores in many seasons and a season has many heroes, but each hero gets only one row per season. The course's completions table does the same with PRIMARY KEY (hero_id, quest_id): one row per hero per quest.

Why bother?

Constraints catch bugs where they happen. Without them, one buggy program quietly saves bad data and you find out weeks later, when a report is wrong. With them, the bad INSERT fails immediately with a clear message, and every app that writes to the database gets the same protection. To see a table's rules, read its definition: SELECT sql FROM sqlite_master WHERE name = 'bounties';.

Common mistakes

  • Expecting UNIQUE to forbid empty values. UNIQUE allows any number of NULLs. Add NOT NULL when a value is required.
  • Off-by-one checks. "From 1 to 100" includes both ends: BETWEEN 1 AND 100, or speed >= 1 AND speed <= 100. speed > 1 would reject 1.
  • Forgetting the quotes on a text default. Write DEFAULT 'open', with quotes like any other text value.
  • Planning to add rules later. SQLite can't add NOT NULL or CHECK to an existing column, so decide on them when you create the table.

Assignment

  1. Create the table mounts for the realm's stables, with these columns in this order:

    Column Type Rules
    id INTEGER primary key
    name TEXT required; no two mounts may share a name
    species TEXT required
    speed INTEGER required; from 1 to 100, both included
    stable TEXT required; 'Eldermoor' when no stable is given
  2. Add three mounts (no ids):

    • 'Thunderhoof', a 'horse' with speed 60, with no stable given
    • 'Skyfin', a 'griffin' with speed 95, in the 'Sunreach' stable
    • 'Pebble', a 'tortoise' with speed 3, with no stable given

Premium lesson

Unlock the full Learn SQL course

  • All 30 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 7 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Keep learning

Need a quick reminder? The SQL cheat sheet has every topic of Learn SQL on one page.

Lesson last updated on .

Write code ↓
SQL+20 XP

Lesson 23 is part of the full course. The first 7 lessons are free.

Premium lesson

Unlock the full Learn SQL course

  • All 30 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 7 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.