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);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;| id | id | name |
|---|---|---|
| 1 | 1 | Drinks |
| 2 | 2 | Bakery |
| 3 | 3 | Snacks |
| 4 | 4 | Stationery |
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;| code | percent |
|---|---|
| NULL | 10 |
| NULL | 20 |
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;| id | name |
|---|---|
| 1 | Somchai |
| 2 | Malee |
| 3 | Pim |
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;| id | name |
|---|---|
| 1 | Somchai |
| 2 | Malee |
| 4 | Pim |
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;| id | name | level | points | joined_today | |
|---|---|---|---|---|---|
| 1 | Somchai | silver | 0 | 1 | NULL |
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');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);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');INSERT INTO member (name, email) VALUES ('Anan W.', 'anan@example.com');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;| id | name | |
|---|---|---|
| 1 | Somchai | NULL |
| 2 | Anan | anan@example.com |
| 3 | Pim | NULL |
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);INSERT INTO supplier_price (supplier, product_id, cost) VALUES ('Hill Farm', 1, 31);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');INSERT INTO promo (name, percent, starts, ends) VALUES ('Everything free', 100, '2026-12-01', '2026-12-02');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');Rules are checked on UPDATE too, not only on INSERT:
UPDATE promo SET percent = percent * 10;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;| product | qty | price | discount | total | code |
|---|---|---|---|---|---|
| Coffee | 2 | 55.0 | 10.0 | 100.0 | COF |
| Pen | 10 | 15.0 | 0.0 | 150.0 | PEN |
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;| product | qty | total |
|---|---|---|
| Coffee | 3 | 155.0 |
| Pen | 10 | 150.0 |
VIRTUAL(the default): worked out each time the row is read; takes no room on the disk.STORED: worked out when the row is written and kept in the file; reading is quicker, the file a little bigger.
A generated column can't be given a value:
INSERT INTO sale_line (product, qty, price, total) VALUES ('Tea', 1, 45, 45);The messages, at a glance
| Rule | What it says | The error when it is broken |
|---|---|---|
PRIMARY KEY | no two rows the same | UNIQUE constraint failed: table.column |
NOT NULL | must have a value | NOT NULL constraint failed: table.column |
UNIQUE | no repeats (NULLs allowed) | UNIQUE constraint failed: table.column |
CHECK | the condition must not be false | CHECK constraint failed: condition or name |
STRICT type | the value must be the column's type | cannot store TEXT value in INTEGER column table.column |
FOREIGN KEY | must 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.
- Make a table
review:idas the rowid,product_idandcustomer_idthat must be there,starsthat must be from 1 to 5, and acommentthat may be empty. One customer may review a product only once. - Add a 5-star review of product 1 by customer 2, with no comment, and look at it.
- Make a table
price_tagwithprice REAL NOT NULLand a generated columnwith_vat, the price plus 7% rounded to 2 places. Add the price 55 and seewith_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;| id | product_id | customer_id | stars | comment |
|---|---|---|---|---|
| 1 | 1 | 2 | 5 | NULL |
| price | with_vat |
|---|---|
| 55.0 | 58.85 |
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