Database Primary and Foreign Key
Database Primary and Foreign Key
In this tutorial, we will discuss about Primary and Foreign Key. The strict relational database model requires that the relation must have unique tuples. No two rows can be identical or the database wouldn’t be able to distinguish one row from the other.Most databases are less strict, that means they allow a database table to contain duplicate rows and a database table can exist without a key. Note that this requirement is not enforced in SQL.
Keys
A key is a column or combination of columns that uniquely identify each tuple. The most important ones are:
- Primary Key
- Foreign Key
Candidate Keys
A candidate key is a column/set of columns that can uniquely identify a row within the table. A table can have multiple candidate keys.
Primary Key
A primary key or just key is a column or set of columns in a table that can uniquely identify a row within the table. The primary key is a candidate key that best defines exactly one unique row in the table.
Columns in the primary key cannot contain NULL values. To implement a primary key, the database allows us to create a Primary Key Constraint. As mentioned earlier, in SQL language tables are not required to have primary keys. However, this is enforced as soon as the primary key constraint is added to the table.
Example:
Let’s consider the City table from the world MySQL database. The column ID is the primary key for the table. In fact, it is a surrogate primary key. ID column is a surrogate primary key used to uniquely identify each city in the table.
A surrogate key is an artificially generated key. For example, ID numbers, GUID,etc are always surrogate keys which are generated automatically for each row in the table.
Example
Table definition::
mysql> SHOW CREATE TABLE City \G
Create Table: CREATE TABLE `city` (
`ID` int NOT NULL AUTO_INCREMENT,
`Name` char(35) NOT NULL DEFAULT ”,
`CountryCode` char(3) NOT NULL DEFAULT ”,
`District` char(20) NOT NULL DEFAULT ”,
`Population` int NOT NULL DEFAULT ‘0’,
PRIMARY KEY (`ID`),
KEY `CountryCode` (`CountryCode`),
CONSTRAINT `city_ibfk_1` FOREIGN KEY (`CountryCode`) REFERENCES `country` (`Code`)
) ENGINE=InnoDB AUTO_INCREMENT=4080 DEFAULT CHARSET=latin1
Foreign Key
A primary key in one database table can be referenced by a primary key in another table The referencing key is called a foreign key. We can connect the two tables using the foreign key.
Example: In the above table CountryCode is the FOREIGN KEY that references the Code column in the City table. A foreign key identifying the country that the city belongs to.
—
MySQL Tutorials
MySQL Tutorials on this website:
https://www.testingdocs.com/mysql-tutorials-for-beginners/