How to identify composite primary key in any MySQL database table?

MySQLMySQLi Database

You can use aggregate function count(*). If it returns a value greater than 1, that would mean the table has composite primary key.

Let us first create a table −

mysql> create table DemoTable1324
   -> (
   -> StudentId int,
   -> StudentName varchar(20),
   -> StudentAge int,
   -> StudentCountryName varchar(20)
   -> );
Query OK, 0 rows affected (0.52 sec)

Here is the query to add composite primary key −

mysql> alter table DemoTable1324 ADD CONSTRAINT constr_IdAgeCountry PRIMARY KEY (StudentId, StudentAge,StudentCountryName);
Query OK, 0 rows affected (1.29 sec)
Records: 0 Duplicates: 0 Warnings: 0

Following is the query to identify composite primary key in any MySQL database table −

mysql> select count(*) AS Total
   -> from information_schema.KEY_COLUMN_USAGE
   -> where table_name='DemoTable1324' and table_schema=database();

This will produce the following output −

+-------+
| Total |
+-------+
|     3 |
+-------+
1 row in set, 2 warnings (0.76 sec)
raja
Published on 05-Nov-2019 10:58:38
Advertisements