MySQL Constraints

Rules for data.

MySQL Constraints

SQL constraints are used to specify rules for the data in a table.

Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data.

Common 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 a NOT NULL and UNIQUE
  • FOREIGN KEY - Prevents actions that would destroy links between tables
  • CHECK - Ensures that the values in a column satisfy a specific condition
  • DEFAULT - Sets a default value for a column if no value is specified
  • CREATE INDEX - Used to create and retrieve data from the database very quickly

Example

CREATE TABLE Persons (ID int NOT NULL, LastName varchar(255) NOT NULL, PRIMARY KEY (ID));