Keys and constraints
Constraints are rules the database enforces for you, so bad data can't get in, however it arrives:
CREATE TABLE warehouses (
id INTEGER PRIMARY KEY,
name VARCHAR NOT NULL UNIQUE,
city VARCHAR NOT NULL,
capacity INTEGER CHECK (capacity > 0)
)PRIMARY KEY: identifies each row. It must be unique and can't be NULL.NOT NULL: the column must always have a value.UNIQUE: no two rows can share the value.UNIQUE (a, b)at the end of the table means the pair must be unique.CHECK (…): any rule you can write as a condition.
A foreign key says a column must match a row in another table:
CREATE TABLE stock_locations (
id INTEGER PRIMARY KEY,
warehouse_id INTEGER NOT NULL REFERENCES warehouses (id),
aisle VARCHAR NOT NULL
)Now a stock location can't point at a warehouse that doesn't exist, and a warehouse can't be deleted while locations still use it. The column it points at must be a primary key (or unique).
Brightwell's own tables were loaded without constraints, which is exactly how planted problems like payments for invoices that don't exist got in. Constraints are the cheapest data-quality check there is.