21. Constraints: rules that keep data right

A table can carry rules that every row must keep: what can't be empty, what can't repeat, what must be true. The database checks them on every change, whichever program makes it.

A program can check its data before writing it, but there is usually more than one program, and people make mistakes. A rule written in the table (a constraint) is checked by the database itself, on every INSERT and UPDATE, from anywhere. A row that breaks one is refused with an error, as chapter 16 showed. This chapter goes through each kind; foreign keys, the rules between tables, have chapter 22 to themselves.

PRIMARY KEY and the rowid

A primary key is what tells one row from every other: no two rows may have the same one. The shop's tables use one number, id INTEGER PRIMARY KEY. A key can also be several columns together: in order_item it is (order_id, product_id), so one order can't hold the same product on two lines:

INSERT INTO order_item (order_id, product_id, qty, price) VALUES (1, 1, 3, 55);
Error: UNIQUE constraint failed: order_item.order_id, order_item.product_id

Under the hood, every SQLite table (unless made WITHOUT ROWID) has a hidden number for each row, the rowid, and keeps its rows in rowid order. A column declared exactly INTEGER PRIMARY KEY is not a separate column: it is the rowid under another name. That is why it is filled in by itself (chapter 16) and why looking a row up by it is the fastest way there is:

SELECT rowid, id, name FROM category;
ididname
11Drinks
22Bakery
33Snacks
44Stationery
4 rows

The first two columns are the same numbers, and even the heading of rowid comes out as id: they are one column with two names.

A PRIMARY KEY that is not INTEGER PRIMARY KEY lets NULL in, an old SQLite habit kept so that old programs still work. Write NOT NULL beside it:

code TEXT NOT NULL PRIMARY KEY

(In a STRICT table, chapter 20, a primary key is always NOT NULL.)

Here is that old habit at work, in a table of discount codes whose key is a text:

CREATE TABLE coupon (
  code    TEXT PRIMARY KEY,
  percent INTEGER
);
INSERT INTO coupon (code, percent) VALUES (NULL, 10), (NULL, 20);
SELECT * FROM coupon;
codepercent
NULL10
NULL20
2 rows

Two rows with no code at all, and neither can ever be found by its code.

AUTOINCREMENT: numbers never used twice

Without anything more, a new INTEGER PRIMARY KEY is the largest number in the table plus one. So when the last row is deleted, the next row gets its number again. Watch with a table of queue tickets:

CREATE TABLE ticket (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
INSERT INTO ticket (name) VALUES ('Somchai'), ('Malee'), ('Anan');
DELETE FROM ticket WHERE id = 3;
INSERT INTO ticket (name) VALUES ('Pim');
SELECT * FROM ticket;
idname
1Somchai
2Malee
3Pim
3 rows

Pim got number 3, Anan's old number. Write AUTOINCREMENT after INTEGER PRIMARY KEY and the database remembers the largest number it ever gave (in a small table, sqlite_sequence), so a number is never given again:

CREATE TABLE ticket2 (
  id   INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL
);
INSERT INTO ticket2 (name) VALUES ('Somchai'), ('Malee'), ('Anan');
DELETE FROM ticket2 WHERE id = 3;
INSERT INTO ticket2 (name) VALUES ('Pim');
SELECT * FROM ticket2;
idname
1Somchai
2Malee
4Pim
3 rows

Pim got 4. Use AUTOINCREMENT when a number leaves the database and must always mean the same thing: an invoice number, a receipt, a number printed on paper or sent to another system. Elsewhere you don't need it: it costs a little extra work on every INSERT, and SQLite's own advice is to leave it out unless you need it.

NOT NULL and DEFAULT

NOT NULL says the column must have a value. DEFAULT gives the value a row gets when the INSERT leaves the column out. A member table for the shop's loyalty card:

CREATE TABLE member (
  id     INTEGER PRIMARY KEY,
  name   TEXT NOT NULL,
  level  TEXT NOT NULL DEFAULT 'silver',
  points INTEGER NOT NULL DEFAULT 0,
  joined TEXT NOT NULL DEFAULT CURRENT_DATE,
  email  TEXT UNIQUE
);
INSERT INTO member (name) VALUES ('Somchai');
SELECT id, name, level, points, joined = date('now') AS joined_today, email FROM member;
idnamelevelpointsjoined_todayemail
1Somchaisilver01NULL
1 row

Only the name was given; the level, the points and the day joined came from the defaults (CURRENT_DATE is today, worked out when the row is added), and email, which has no default, is NULL. A default can be a value, CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, or any expression in brackets, like DEFAULT (date('now', '+30 days')).

A member with no name is refused:

INSERT INTO member (level) VALUES ('gold');
Error: NOT NULL constraint failed: member.name

A default is used only when the column is left out. Writing NULL for it is not leaving it out: it asks for NULL, and NOT NULL refuses it.

INSERT INTO member (name, level) VALUES ('Malee', NULL);
Error: NOT NULL constraint failed: member.level

UNIQUE: no repeats

UNIQUE says no two rows may have the same value in the column. The member table above has email TEXT UNIQUE, so two members can't share an email:

INSERT INTO member (name, email) VALUES ('Anan', 'anan@example.com');
✓ 1 row changed
INSERT INTO member (name, email) VALUES ('Anan W.', 'anan@example.com');
Error: UNIQUE constraint failed: member.email

The rule counts NULL as "unknown", and two unknowns are not equal, so a UNIQUE column takes as many NULLs as you like. Somchai has no email yet, and neither does the next member:

INSERT INTO member (name) VALUES ('Pim');
SELECT id, name, email FROM member;
idnameemail
1SomchaiNULL
2Anananan@example.com
3PimNULL
3 rows

UNIQUE can cover several columns together, written after the columns: then only the same values in all of them together count as a repeat. A list of what each supplier charges for each product: a supplier has many products and a product many suppliers, but one supplier gives one product one price:

CREATE TABLE supplier_price (
  supplier   TEXT NOT NULL,
  product_id INTEGER NOT NULL,
  cost       REAL NOT NULL,
  UNIQUE (supplier, product_id)
);
INSERT INTO supplier_price (supplier, product_id, cost) VALUES
  ('Doi Coffee Co.', 1, 30), ('Doi Coffee Co.', 2, 25), ('Hill Farm', 1, 32);
✓ 3 rows changed
INSERT INTO supplier_price (supplier, product_id, cost) VALUES ('Hill Farm', 1, 31);
Error: UNIQUE constraint failed: supplier_price.supplier, supplier_price.product_id

CHECK: anything that must be true

CHECK (condition) takes any condition, like a WHERE, and refuses a row for which it is false. The shop's promotions give from 1 to 90 percent off, and a promotion can't end before it starts:

CREATE TABLE promo (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  percent INTEGER NOT NULL CHECK (percent BETWEEN 1 AND 90),
  ends    TEXT NOT NULL,
  starts  TEXT NOT NULL,
  CONSTRAINT dates_in_order CHECK (starts <= ends)
);
INSERT INTO promo (name, percent, starts, ends) VALUES ('Coffee week', 15, '2026-12-01', '2026-12-07');
✓ 1 row changed
INSERT INTO promo (name, percent, starts, ends) VALUES ('Everything free', 100, '2026-12-01', '2026-12-02');
Error: CHECK constraint failed: percent BETWEEN 1 AND 90

The error quotes the condition that failed. A rule over several columns is written after the columns, and CONSTRAINT name gives it a name, which is then what the error shows:

INSERT INTO promo (name, percent, starts, ends) VALUES ('Back to front', 10, '2026-12-31', '2026-12-01');
Error: CHECK constraint failed: dates_in_order

Rules are checked on UPDATE too, not only on INSERT:

UPDATE promo SET percent = percent * 10;
Error: CHECK constraint failed: percent BETWEEN 1 AND 90

A CHECK refuses a row only when its condition is false. When it is NULL (unknown), the row goes in. CHECK (percent BETWEEN 1 AND 90) lets a NULL percent through; that is why percent here is also NOT NULL.

Generated columns

A generated column is worked out from the other columns of its row, by itself; nobody writes it. GENERATED ALWAYS AS (expression), or just AS (expression):

CREATE TABLE sale_line (
  product  TEXT NOT NULL,
  qty      INTEGER NOT NULL,
  price    REAL NOT NULL,
  discount REAL NOT NULL DEFAULT 0,
  total    REAL GENERATED ALWAYS AS (qty * price - discount) VIRTUAL,
  code     TEXT AS (upper(substr(product, 1, 3))) STORED
);
INSERT INTO sale_line (product, qty, price, discount) VALUES ('Coffee', 2, 55, 10), ('Pen', 10, 15, 0);
SELECT * FROM sale_line;
productqtypricediscounttotalcode
Coffee255.010.0100.0COF
Pen1015.00.0150.0PEN
2 rows

The total and the code were never given, yet each row has them, and they follow the row: change qty and the total changes with it.

UPDATE sale_line SET qty = 3 WHERE product = 'Coffee';
SELECT product, qty, total FROM sale_line;
productqtytotal
Coffee3155.0
Pen10150.0
2 rows

A generated column can't be given a value:

INSERT INTO sale_line (product, qty, price, total) VALUES ('Tea', 1, 45, 45);
Error: cannot INSERT into generated column "total"

The messages, at a glance

RuleWhat it saysThe error when it is broken
PRIMARY KEYno two rows the sameUNIQUE constraint failed: table.column
NOT NULLmust have a valueNOT NULL constraint failed: table.column
UNIQUEno repeats (NULLs allowed)UNIQUE constraint failed: table.column
CHECKthe condition must not be falseCHECK constraint failed: condition or name
STRICT typethe value must be the column's typecannot store TEXT value in INTEGER column table.column
FOREIGN KEYmust point at a row that is there (chapter 22)FOREIGN KEY constraint failed

Read the error: it names the table and the column, or the condition, that was broken.

  1. Make a table review: id as the rowid, product_id and customer_id that must be there, stars that must be from 1 to 5, and a comment that may be empty. One customer may review a product only once.
  2. Add a 5-star review of product 1 by customer 2, with no comment, and look at it.
  3. Make a table price_tag with price REAL NOT NULL and a generated column with_vat, the price plus 7% rounded to 2 places. Add the price 55 and see with_vat.
Show the answer
CREATE TABLE review (
  id          INTEGER PRIMARY KEY,
  product_id  INTEGER NOT NULL,
  customer_id INTEGER NOT NULL,
  stars       INTEGER NOT NULL CHECK (stars BETWEEN 1 AND 5),
  comment     TEXT,
  UNIQUE (product_id, customer_id)
);
INSERT INTO review (product_id, customer_id, stars) VALUES (1, 2, 5);
SELECT * FROM review;
CREATE TABLE price_tag (
  price    REAL NOT NULL,
  with_vat REAL AS (round(price * 1.07, 2))
);
INSERT INTO price_tag (price) VALUES (55);
SELECT * FROM price_tag;
idproduct_idcustomer_idstarscomment
1125NULL
1 row
pricewith_vat
55.058.85
1 row

Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made