How to identify foreign key in MySQL DB?


Let us first create a table −

mysql> create table DemoTable1 (Id int NOT NULL PRIMARY KEY,EmployeeName varchar(100));
Query OK, 0 rows affected (0.50 sec)

Following is the query to create a second table with foreign key constraints −

mysql> create table DemoTable2
   (
      Id int NOT NULL,
      StreetName varchar(100),
      CityName varchar(100),
      CountryName varchar(100),
      PinCode int,
      EmployeeId int,
      PRIMARY KEY(Id),
      FOREIGN KEY (Id) REFERENCES DemoTable1(Id)
   );
Query OK, 0 rows affected (0.46 sec)

Following is the query to identify the foreign key in MySQL DB −

mysql> show create table DemoTable2\G

This will produce the following output −

*************************** 1. row ***************************
Table: DemoTable2
Create Table: CREATE TABLE `demotable2` (
   `Id` int(11) NOT NULL,
   `StreetName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
   `CityName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
   `CountryName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
   `PinCode` int(11) DEFAULT NULL,
   `EmployeeId` int(11) DEFAULT NULL,
   PRIMARY KEY (`Id`),
   CONSTRAINT `demotable2_ibfk_1` FOREIGN KEY (`Id`) REFERENCES `demotable1`
(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
1 row in set (0.00 sec)

Updated on: 22-Aug-2019

328 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements