- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Understanding Basics of Foreign Keys in MySQL?
The foreign key can be used to create a relationship between tables. The foreign key relationship can be one to one or one to many. A foreign key matches another field of another table.
One to One relationship − One record from one table will be linked to one record in another table.
One to Many relationships − One record will be linked to multiple records in another table.
The following is an example. First, we will create a table. The CREATE command is used to create a table.
mysql> create table tblF - > ( - > id int , - > FirstName varchar(100), - > FK_PK int - > ); Query OK, 0 rows affected (0.57 sec)
To create a second table.
mysql> create table tblP - > ( - > FK_PK int, - > LastName varchar(100), - > primary key(FK_PK) - > ); Query OK, 0 rows affected (0.94 sec)
The following is the syntax to create a foreign key.
mysql> ALTER table tblF add constraint ConstFK foreign key(FK_PK) references tblP(FK_PK); Query OK, 0 rows affected (2.17 sec) Records: 0 Duplicates: 0 Warnings: 0
Check if foreign key has been created with the help of DESC command.
mysql> DESC tblF;
The following is the output.
+-----------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+--------------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | FirstName | varchar(100) | YES | | NULL | | | FK_PK | int(11) | YES | MUL | NULL | | +-----------+--------------+------+-----+---------+-------+ 3 rows in set (0.05 sec)
- Related Articles
- Basics of Foreign Keys in MySQL?
- Using Foreign Keys in MySQL
- Explain the concept of foreign keys with examples(DBMS)?
- How to find all the foreign keys of a DB2 table TAB1?
- How do I see all foreign keys to a table column?
- Understanding base64 encode in MySQL?
- Get a list of Foreign Key constraints in MySQL
- MySQL Syntax to create Foreign Key?
- How to identify foreign key in MySQL DB?
- Searching on Two Keys in MySQL
- Basics of React.js Routing
- Basics of File Handling in C
- HTML Basics
- Microcomputer Basics
- Microprocessor Basics

Advertisements