Database Tables and Keys · Lesson 15 of 112

Database NOT NULL, DEFAULT and CHECK

What you will learn

  • What a constraint is
  • How NOT NULL, DEFAULT and CHECK work
  • How to write a CHECK rule across several columns
  • Why the database should enforce rules even when your program checks them too

1. Constraints: rules the database enforces

A constraint is a rule attached to a table. When someone inserts or changes a row that breaks it, the database refuses the change and nothing is saved. You have met PRIMARY KEY and UNIQUE. Three more:

Constraint Rule
NOT NULL the column must have a value
DEFAULT x if no value is given, use x
CHECK (condition) the condition must be true (or unknown) for the row

2. NOT NULL and DEFAULT

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It uses real tables and a few small tables of its own in your browser's copy; run the examples from top to bottom, and press Reset data to start again.

A small table of your own shows both rules. customer must have a value; status and quantity fill themselves in when left out:

CREATE TABLE parcels (
    id       INTEGER PRIMARY KEY,
    customer TEXT NOT NULL,
    status   TEXT NOT NULL DEFAULT 'new',
    quantity INTEGER NOT NULL DEFAULT 1
);
INSERT INTO parcels (customer) VALUES ('Rina');
INSERT INTO parcels (customer, quantity) VALUES ('Sam', 5);
SELECT * FROM parcels ORDER BY id;
id  customer  status  quantity
--  --------  ------  --------
 1  Rina      new            1
 2  Sam       new            5
(2 rows)

The row with no customer is refused, because customer has NOT NULL and no default:

INSERT INTO parcels (status) VALUES ('paid');
IntegrityError: NOT NULL constraint failed: parcels.customer
CREATE TABLE parcels (
    id       INTEGER PRIMARY KEY,
    customer TEXT NOT NULL,
    status   TEXT NOT NULL DEFAULT 'new',
    quantity INTEGER NOT NULL DEFAULT 1
);
INSERT INTO parcels (customer) VALUES ('Rina');
INSERT INTO parcels (customer, quantity) VALUES ('Sam', 5);
SELECT * FROM parcels ORDER BY id;
id  customer  status  quantity
--  --------  ------  --------
 1  Rina      new            1
 2  Sam       new            5
(2 rows)

The row with no customer is refused, because customer has NOT NULL and no default:

INSERT INTO parcels (status) VALUES ('paid');
IntegrityError: NOT NULL constraint failed: parcels.customer
CREATE TABLE parcels (
    id       INTEGER PRIMARY KEY,
    customer TEXT NOT NULL,
    status   TEXT NOT NULL DEFAULT 'new',
    quantity INTEGER NOT NULL DEFAULT 1
);
INSERT INTO parcels (customer) VALUES ('Rina');
INSERT INTO parcels (customer, quantity) VALUES ('Sam', 5);
SELECT * FROM parcels ORDER BY id;
id  customer  status  quantity
--  --------  ------  --------
 1  Rina      new            1
 2  Sam       new            5
(2 rows)

The row with no customer is refused, because customer has NOT NULL and no default:

INSERT INTO parcels (status) VALUES ('paid');
IntegrityError: NOT NULL constraint failed: parcels.customer

Rina's row got status = 'new' and quantity = 1 automatically.

Note: DEFAULT applies only when you leave the column out. If you explicitly insert NULL into a NOT NULL column, it is still refused:

INSERT INTO parcels (customer, quantity) VALUES ('Lee', NULL);
IntegrityError: NOT NULL constraint failed: parcels.quantity
INSERT INTO parcels (customer, quantity) VALUES ('Lee', NULL);
IntegrityError: NOT NULL constraint failed: parcels.quantity
INSERT INTO parcels (customer, quantity) VALUES ('Lee', NULL);
IntegrityError: NOT NULL constraint failed: parcels.quantity

The sample tables use the same rules:

products.name is NOT NULL, while stock and is_active have defaults (0 and 1). Leave the name out and the insert is refused; leave the defaults out and they are filled in:

INSERT INTO products (sku, category_id, supplier_id, price, cost, added_on)
VALUES ('SKU-9001', 1, 1, 9.5, 4.0, '2026-01-01');
IntegrityError: NOT NULL constraint failed: products.name
INSERT INTO products (sku, name, category_id, supplier_id, price, cost, added_on)
VALUES ('SKU-9001', 'Test tray', 1, 1, 9.5, 4.0, '2026-01-01');
SELECT sku, name, stock, is_active FROM products WHERE sku = 'SKU-9001';
sku       name       stock  is_active
--------  ---------  -----  ---------
SKU-9001  Test tray      0          1
(1 row)

accounts.opened_on is NOT NULL, while status has a default ('open'). Leave the date out and the insert is refused; leave the status out and it is filled in:

INSERT INTO accounts (customer_id, branch_id, account_type, balance_cents)
VALUES (1, 1, 'savings', 0);
IntegrityError: NOT NULL constraint failed: accounts.opened_on
INSERT INTO accounts (customer_id, branch_id, account_type, opened_on, balance_cents)
VALUES (1, 1, 'savings', '2026-01-01', 0);
SELECT account_id, account_type, status FROM accounts ORDER BY account_id DESC LIMIT 1;
account_id  account_type  status
----------  ------------  ------
       451  savings       open
(1 row)

students.birth_date is NOT NULL, and guardian_name may be empty. Leave the birth date out and the insert is refused; leave the guardian out and it simply stays NULL:

INSERT INTO students (first_name, last_name, enrolled_year)
VALUES ('Test', 'Student', 2026);
IntegrityError: NOT NULL constraint failed: students.birth_date
INSERT INTO students (first_name, last_name, birth_date, enrolled_year)
VALUES ('Test', 'Student', '2012-05-01', 2026);
SELECT first_name, birth_date, email, guardian_name FROM students ORDER BY student_id DESC LIMIT 1;
first_name  birth_date  email  guardian_name
----------  ----------  -----  -------------
Test        2012-05-01  NULL   NULL
(1 row)

3. CHECK

CHECK tests any condition on the row. The sample tables have several:

products.price has CHECK (price > 0). A negative price is refused:

UPDATE products SET price = -5 WHERE product_id = 1;
IntegrityError: CHECK constraint failed: price > 0

accounts.balance_cents has CHECK (balance_cents >= 0). A negative balance is refused:

UPDATE accounts SET balance_cents = -100 WHERE account_id = 1;
IntegrityError: CHECK constraint failed: balance_cents >= 0

enrollments.grade has CHECK (grade BETWEEN 0 AND 100). A grade of 120 is refused:

UPDATE enrollments SET grade = 120 WHERE student_id = 1 AND section_id = 19;
IntegrityError: CHECK constraint failed: grade BETWEEN 0 AND 100

Now a table of your own, with a list rule:

CREATE TABLE goods (
    id          INTEGER PRIMARY KEY,
    name        TEXT NOT NULL,
    price_cents INTEGER NOT NULL CHECK (price_cents >= 0),
    size        TEXT CHECK (size IN ('S', 'M', 'L'))
);
INSERT INTO goods (name, price_cents, size) VALUES ('pen', 1050, 'M');
(1 row changed)
INSERT INTO goods (name, price_cents, size) VALUES ('gift', -5, 'S');
IntegrityError: CHECK constraint failed: price_cents >= 0
INSERT INTO goods (name, price_cents, size) VALUES ('shirt', 99900, 'XL');
IntegrityError: CHECK constraint failed: size IN ('S', 'M', 'L')
INSERT INTO goods (name, price_cents, size) VALUES ('sticker', 500, NULL);
SELECT * FROM goods ORDER BY id;
id  name     price_cents  size
--  -------  -----------  ----
 1  pen             1050  M
 2  sticker          500  NULL
(2 rows)
CREATE TABLE goods (
    id          INTEGER PRIMARY KEY,
    name        TEXT NOT NULL,
    price_cents INTEGER NOT NULL CHECK (price_cents >= 0),
    size        TEXT CHECK (size IN ('S', 'M', 'L'))
);
INSERT INTO goods (name, price_cents, size) VALUES ('pen', 1050, 'M');
(1 row changed)
INSERT INTO goods (name, price_cents, size) VALUES ('gift', -5, 'S');
IntegrityError: CHECK constraint failed: price_cents >= 0
INSERT INTO goods (name, price_cents, size) VALUES ('shirt', 99900, 'XL');
IntegrityError: CHECK constraint failed: size IN ('S', 'M', 'L')
INSERT INTO goods (name, price_cents, size) VALUES ('sticker', 500, NULL);
SELECT * FROM goods ORDER BY id;
id  name     price_cents  size
--  -------  -----------  ----
 1  pen             1050  M
 2  sticker          500  NULL
(2 rows)
CREATE TABLE goods (
    id          INTEGER PRIMARY KEY,
    name        TEXT NOT NULL,
    price_cents INTEGER NOT NULL CHECK (price_cents >= 0),
    size        TEXT CHECK (size IN ('S', 'M', 'L'))
);
INSERT INTO goods (name, price_cents, size) VALUES ('pen', 1050, 'M');
(1 row changed)
INSERT INTO goods (name, price_cents, size) VALUES ('gift', -5, 'S');
IntegrityError: CHECK constraint failed: price_cents >= 0
INSERT INTO goods (name, price_cents, size) VALUES ('shirt', 99900, 'XL');
IntegrityError: CHECK constraint failed: size IN ('S', 'M', 'L')
INSERT INTO goods (name, price_cents, size) VALUES ('sticker', 500, NULL);
SELECT * FROM goods ORDER BY id;
id  name     price_cents  size
--  -------  -----------  ----
 1  pen             1050  M
 2  sticker          500  NULL
(2 rows)
  • A negative price is refused.
  • The size XL is refused because it is not in the list.
  • sticker with size NULL is accepted: a CHECK rule is violated only when the condition is false. If it is unknown (as with NULL, lesson 2.3), the row passes. Add NOT NULL when a value is required.

Rules across columns

A CHECK can compare columns in the same row:

CREATE TABLE bookings (
    id        INTEGER PRIMARY KEY,
    start_day TEXT NOT NULL,
    end_day   TEXT NOT NULL,
    CHECK (end_day >= start_day)
);
INSERT INTO bookings (start_day, end_day) VALUES ('2026-03-01', '2026-03-05');
(1 row changed)
INSERT INTO bookings (start_day, end_day) VALUES ('2026-03-10', '2026-03-02');
IntegrityError: CHECK constraint failed: end_day >= start_day
CREATE TABLE bookings (
    id        INTEGER PRIMARY KEY,
    start_day TEXT NOT NULL,
    end_day   TEXT NOT NULL,
    CHECK (end_day >= start_day)
);
INSERT INTO bookings (start_day, end_day) VALUES ('2026-03-01', '2026-03-05');
(1 row changed)
INSERT INTO bookings (start_day, end_day) VALUES ('2026-03-10', '2026-03-02');
IntegrityError: CHECK constraint failed: end_day >= start_day
CREATE TABLE bookings (
    id        INTEGER PRIMARY KEY,
    start_day TEXT NOT NULL,
    end_day   TEXT NOT NULL,
    CHECK (end_day >= start_day)
);
INSERT INTO bookings (start_day, end_day) VALUES ('2026-03-01', '2026-03-05');
(1 row changed)
INSERT INTO bookings (start_day, end_day) VALUES ('2026-03-10', '2026-03-02');
IntegrityError: CHECK constraint failed: end_day >= start_day

A booking cannot end before it starts. (The comparison works because dates are stored as YYYY-MM-DD, lesson 2.2.)

The Bank has such a rule on transfers: money cannot be moved from an account to itself.

INSERT INTO transfers (from_account, to_account, amount_cents, created_on, status)
VALUES (1, 1, 500, '2026-01-01', 'done');
IntegrityError: CHECK constraint failed: from_account <> to_account

4. Naming a rule

Give a rule a name so the error message says what went wrong:

CREATE TABLE savings (
    id            INTEGER PRIMARY KEY,
    balance_cents INTEGER NOT NULL,
    CONSTRAINT balance_not_negative CHECK (balance_cents >= 0)
);
(done)
INSERT INTO savings (balance_cents) VALUES (-100);
IntegrityError: CHECK constraint failed: balance_not_negative
CREATE TABLE savings (
    id            INTEGER PRIMARY KEY,
    balance_cents INTEGER NOT NULL,
    CONSTRAINT balance_not_negative CHECK (balance_cents >= 0)
);
(done)
INSERT INTO savings (balance_cents) VALUES (-100);
IntegrityError: CHECK constraint failed: balance_not_negative
CREATE TABLE savings (
    id            INTEGER PRIMARY KEY,
    balance_cents INTEGER NOT NULL,
    CONSTRAINT balance_not_negative CHECK (balance_cents >= 0)
);
(done)
INSERT INTO savings (balance_cents) VALUES (-100);
IntegrityError: CHECK constraint failed: balance_not_negative

5. Why not just check in the program?

Your program should check input too, to give friendly messages. But the database enforces the rule for everything: the website, a script, another developer's tool, a manual fix at midnight. A rule that lives only in one program is a rule that can be bypassed by another. Put the rules that must never be broken in the database, and keep the friendly messages in the application.

A too-strict rule can block valid data. Write rules that state facts that are always true (a price is not negative), not guesses (a name is under 20 letters).

Worked example: constrain a students table

Requirements: every student has a name; the status is active unless said otherwise and must be active, left or graduated; the year of admission is between 2000 and 2100.

CREATE TABLE students (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'active'
        CHECK (status IN ('active', 'left', 'graduated')),
    admitted INTEGER NOT NULL CHECK (admitted BETWEEN 2000 AND 2100)
)

Inserting (name, admitted) only gives status = 'active'. Inserting status = 'gone' is refused. The table is made up.

Common mistakes

  • Rules only in the app, where other tools bypass them.
  • Overly strict CHECKs (name length limits that real names break).
  • Forgetting that NULL passes a CHECK. Combine with NOT NULL.
  • Using DEFAULT to hide missing data (a default of 0 can look like real data).

Key takeaways

  • Constraints are rules the database enforces on every change.
  • NOT NULL demands a value; DEFAULT supplies one when the column is left out; CHECK tests a condition.
  • A CHECK passes when the condition is true or unknown, so pair it with NOT NULL.
  • Name your constraints to get clear error messages.
  • Enforce must-never-break rules in the database, not only in the program.

Practice

1. What does DEFAULT 'new' do when you insert a row without a status?

Show answer

The status is stored as 'new'.

2. Does DEFAULT rescue an insert that explicitly gives NULL for a NOT NULL column?

Show answer

No. The default is used only when the column is left out; an explicit NULL is still refused.

3. Write a CHECK that keeps a rating column between 1 and 5.

Show answer

CHECK (rating BETWEEN 1 AND 5)

4. Why did the product with size NULL pass CHECK (size IN ('S','M','L'))?

Show answer

The condition is unknown for NULL, not false, and a CHECK refuses only when the condition is false.

5. Why enforce a rule in the database if the website already checks it?

Show answer

Other programs, scripts and manual edits can write to the database and would bypass the website's check.

6. Give an example of a CHECK rule that is too strict.

Show answer

For example limiting a name to 20 letters, since real names can be longer.