MySQL Primary Key and Foreign Key

MySQL Primary Key and Foreign Key:

The Primary Key is the most widely used constraint. It ensures that the columns on which it is defined must contain unique values for all the rows. The Primary Key column does not allow a NULL value. The Primary Key helps to maintain Entity Integrity in a table.

Foreign Key is used to maintain relationships between tables in RDBMS and ensure referential integrity. A Foreign Key refers to the primary key Column of the same or other table. While defining the foreign key the type of primary key column and foreign key must be the same, however, the name of the column can differ. The tables with the primary key and foreign key are parent and child table respectively. Prior to defining a foreign key on a child table, the primary key must be defined on the parent table. A table must have one or more foreign key constraints.

MySQL Primary Key Syntax:

syntax of MySQL Primary Key

MySQL Foreign Key Syntax:

Syntax of Foreign Key in MySQL

MySQL Primary Key and Foreign Key:

(1) First of all we have created a table. For example- city_table is shown below.

Mysql create city_table

(2) We have created a new table by using a query and mentioning the above table as a foreign key in the new table. For example- student_table is shown below.

MySQL Primary Key and Foreign Key Code unit

(3) Now we insert values into the student_table and city_id acts as a foreign key as shown below.

primary key table link with foreign key table in mysql

Note: If you add any value in the city_id above 5 it shows an error because, in city_table, cn_id only has 5 values.


Programming Languages
Procedure-Oriented Programming
Modular Programming

Create Table in MySQL
MySQL Insert Query (Single Row and Multiple Row)
MySQL Select Query with Where Clause
MySQL– Wikipedia

Comments (No)

Leave a Reply