SQL from Zero › Module 2: DDL: building the structure

Constraints: NOT NULL, UNIQUE, DEFAULT, CHECK

Add rules to columns so bad data can't get in.

Lesson 10 of 33 · about 14 minutes

Video: House rules for your dataThe narrated video for this lesson is coming soon. The lesson below covers the same ideas.

The lesson

A good shop has rules: every parcel needs an address, and no two lockers share a number. Tables have rules too, called constraints. You add them after a column's type, and the database enforces them every time data is added or changed.

ConstraintRuleExample
NOT NULLThis column must always have a valuename TEXT NOT NULL
UNIQUENo two rows may have the same valueemail TEXT UNIQUE
DEFAULTUse this value if none is givencountry TEXT DEFAULT 'Unknown'
CHECKThe value must pass a testprice REAL CHECK (price >= 0)

You can combine them:

CREATE TABLE customers (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  email TEXT UNIQUE,
  country TEXT DEFAULT 'Unknown'
);

Why bother, when you could just be careful? Because databases are used by many people and many apps at once. Rules in the database protect the data even when someone else makes a mistake. It's the C in ACID: consistent.

Key ideas
  • Constraints are rules the database enforces on every change.
  • NOT NULL requires a value, UNIQUE forbids duplicates, DEFAULT fills in a value, CHECK tests a condition.
  • Rules in the database protect data from everyone's mistakes, not just yours.

Practise

Loading practice…

Quick check

1. Which constraint stops two customers from having the same email?

2. What does stock INTEGER DEFAULT 0 do when a book is added without a stock value?

3. Which rule keeps prices from going below zero?