How to get the primary key “column name” of a specific table in MySQL?

MySQLMySQLi Database

Let us first create a table wherein we have a Primary Key CustomerId −

mysql> create table DemoTable
   (
   CustomerId int NOT NULL AUTO_INCREMENT,
   CustomerName varchar(20),
   CustomerAge int,
   CustomerCountryName varchar(100),
   PRIMARY KEY(CustomerId)
   );
Query OK, 0 rows affected (0.94 sec)

Following is the query to get the primary key “column name” of a specific table in MySQL −

mysql> SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = 'DemoTable'
AND CONSTRAINT_NAME = 'PRIMARY';

This will produce the following output −

+-------------+
| COLUMN_NAME |
+-------------+
| CustomerId  |
+-------------+
1 row in set, 2 warnings (0.12 sec)
raja
Published on 03-May-2019 11:21:37
Advertisements