Skip to content

SQL Constraints

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.

  • 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.

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 NULL or CHECK (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_SupplierRef makes the pair of supplier and supplier reference unique, and CHK_PaidAfterInvoiced compares 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.

ALTER TABLE adds a constraint to a table that already exists:

ALTER TABLE Invoices
ADD CONSTRAINT CHK_PositiveAmount CHECK (Amount > 0);

The database checks the existing rows first, and refuses the new rule if any row already breaks it.