Skip to content

SQL CHECK Constraint

CHECK attaches a condition to a table. A row may be inserted or updated only if the condition holds for it.

An invoice amount must be greater than zero:

CREATE TABLE Invoices (
InvoiceID int PRIMARY KEY,
Supplier varchar(100) NOT NULL,
Amount decimal(10, 2) NOT NULL CHECK (Amount > 0),
InvoiceDate date NOT NULL,
PaidDate date
);

An invoice for -50 is refused.

A check can compare columns of the same row. An invoice cannot be paid before it was issued:

CONSTRAINT CHK_PaidAfterInvoiced
CHECK (PaidDate IS NULL OR PaidDate >= InvoiceDate)

The PaidDate IS NULL part lets unpaid invoices through. Once a paid date is set, it must be on or after the invoice date, so recording a payment on 1 March against an invoice dated 4 March is refused.

A condition that comes out as unknown, because a value in it is NULL, counts as passing. Write the NULL case into the condition, as here, so the rule says exactly what you mean.

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

Remove it by name with ALTER TABLE Invoices DROP CONSTRAINT CHK_PositiveAmount;; MySQL also accepts DROP CHECK in place of DROP CONSTRAINT.