In this tutorial, we will learn about MySQL Constraints. A constraint is a restriction placed on one or more column values of a database table. Constraints enforce database integrity rules.
Types of Constraints
- Primary Key
- Foreign Key
The MySQL server will generate a new index to enforce primary key, foreign key, and unique constraints.
PRIMARY KEY constraint defines the column(s) that guarantee uniqueness within a table. Only one primary key is allowed per table.
FOREIGN KEY constraint restrict column(s) to contain only values that match those in another
table’s PRIMARY KEY column. This constraint is used to link database tables with referencing foreign keys.
Let’s take an example from the MySQL world database. The MySQL server allowed to modify the CountryCode value in the CountryLanguage table without changing the corresponding CountryCode value in the City table, then we would end up with rows that no longer point to valid country records (known as orphaned rows).
KEY `CountryCode` (`CountryCode`),
CONSTRAINT `countryLanguage_ibfk_1` FOREIGN KEY (`CountryCode`) REFERENCES `country` (`Code`)
With FOREIGN KEY constraint in place the server will either raise an error if an attempt is made to modify or delete data that if referenced by other tables, or it will propagate the changes
to other tables for you.
UNIQUE constraint is same as PRIMARY KEY except that the columns are allowed to contain NULL values. There can be multiple UNIQUE constraints in one database table.
MySQL Tutorials on this website:
For more information on MySQL Database: