Careeroza
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
| Constraint | Ensures that... |
|---|---|
NOT NULL | a column cannot have a NULL value |
UNIQUE | all values in a column are different |
PRIMARY KEY | NOT NULL + UNIQUE: uniquely identifies each row |
FOREIGN KEY | a value exists in another (parent) table |
CHECK | values satisfy a condition |
DEFAULT | a value is used when none is given |
CREATE INDEX | speeds 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.