Overview of MySQL Constraint Types
Constraints are used to define data rules in a table to ensure the integrity and validity of records. If a data operation violates a constraint, the operation is terminated. Constraints can be defined during table creation using CREATE TABLE or after creation using ALTER TABLE.
There are six primary types of constraints:
- NOT NULL: Ensures a column cannot have a NULL value.
- UNIQUE: Ensures all values in a column are different.
- PRIMARY KEY: A combination of NOT NULL and UNIQUE; uniquely identifies each row and automatically creates an index.
- FOREIGN KEY: Ensures referential integrity between tables.
- CHECK: Ensures values in a column meet a specific condition (applicable in Oracle/newer MySQL versions).
- DEFAULT: Provides a default value if none is specified.
Constraints are further categorized by their scope:
- Column-level constraints: Defined immediately after the column definition. They apply to a single column. All constraints except FOREIGN KEY can be defined at the column level.
- Table-level constraints: Defined independently of column definitions, usually separated by commas. They can apply to multiple columns (composite constraints). Only PRIMARY KEY, FOREIGN KEY, UNIQUE, and CHECK can be defined at the table level.