A constraint is a rule a table enforces on its own data. Once a constraint is declared, the database refuses any insert, update or delete that would break it, whichever application or person tries. Rules kept in the database cannot be bypassed by a program that forgets them.
The constraints
Section titled “The constraints”NOT NULL: the column must always have a value.UNIQUE: no two rows may share a value in the column.PRIMARY KEY: the column identifies each row, so it must be unique and never empty.FOREIGN KEY: the value must match a row in another table.CHECK: the value must pass a condition, such as being greater than zero.DEFAULT: the value to use when an insert gives none. Strictly this fills in data rather than refusing it, but it is declared in the same way.
An index is often listed alongside these. It speeds up searches rather than enforcing a rule, although a unique index does both.
Declaring them
Section titled “Declaring them”Constraints are usually declared when a table is created. A version of the Invoices table from the example database, with rules on every column that needs one:
CREATE TABLE Invoices ( InvoiceID int PRIMARY KEY, ProductionID int NOT NULL REFERENCES Productions (ProductionID), Supplier varchar(100) NOT NULL, SupplierRef varchar(30), Amount decimal(10, 2) NOT NULL CHECK (Amount > 0), InvoiceDate date NOT NULL DEFAULT CURRENT_DATE, PaidDate date, CONSTRAINT UQ_SupplierRef UNIQUE (Supplier, SupplierRef), CONSTRAINT CHK_PaidAfterInvoiced CHECK (PaidDate IS NULL OR PaidDate >= InvoiceDate));The table has two ways of writing a constraint:
- Beside a column, as with
NOT NULLorCHECK (Amount > 0), when the rule concerns that column alone. - On a line of its own, after the columns, when the rule involves several columns.
UQ_SupplierRefmakes the pair of supplier and supplier reference unique, andCHK_PaidAfterInvoicedcompares two dates.
CONSTRAINT name gives a rule a name. Naming is optional, but a named rule appears by name in error messages, and is easy to remove later with ALTER TABLE … DROP CONSTRAINT name.
Adding them later
Section titled “Adding them later”ALTER TABLE adds a constraint to a table that already exists:
ALTER TABLE InvoicesADD CONSTRAINT CHK_PositiveAmount CHECK (Amount > 0);The database checks the existing rows first, and refuses the new rule if any row already breaks it.