Constraints Overview

SQL Constraints

Constraints are rules for the data in a table. If an INSERT or UPDATE breaks a constraint, the database rejects it. Constraints guarantee data accuracy and reliability, no matter which application writes the data.

CREATE TABLE table_name (
    column1 datatype constraint,
    column2 datatype constraint,
    ...
    table_constraint
);

Common Constraints

ConstraintEnsures that...
NOT NULLa column cannot have a NULL value
UNIQUEall values in a column are different
PRIMARY KEYNOT NULL + UNIQUE: uniquely identifies each row
FOREIGN KEYa value exists in another (parent) table
CHECKvalues satisfy a condition
DEFAULTa value is used when none is given
CREATE INDEXspeeds up lookups (not strictly a constraint, covered in Indexes)

Column-level vs Table-level

A constraint can be written next to one column, or at the end of the table definition. Table-level is required when it spans several columns, and lets you give it a name.

CREATE TABLE Enrollments (
  StudentID INT NOT NULL,            -- column-level
  CourseID  INT NOT NULL,
  Grade     CHAR(1),
  CONSTRAINT PK_Enrollment PRIMARY KEY (StudentID, CourseID),   -- table-level, named
  CONSTRAINT CK_Grade CHECK (Grade IN ('A','B','C','D','F'))
);

Tip: Name your constraints (PK_..., FK_..., CK_...). Error messages become readable, and you can drop them by name later.