How to view the primary key fields of a table?

When using a MySQL instance, the following three methods are commonly used to view primary key fields. Select a method based on your needs.

View system tables

Run the following SQL statement to confirm the primary key fields in the system table.

  1. SELECT t.TABLE_NAME,
  2. t.CONSTRAINT_TYPE,
  3. c.COLUMN_NAME,
  4. c.ORDINAL_POSITION
  5. FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS t,
  6. INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS c
  7. WHERE t.TABLE_NAME = c.TABLE_NAME
  8. AND t.CONSTRAINT_TYPE = 'PRIMARY KEY'
  9. AND t.TABLE_NAME='[$Table_Name]'
  10. AND t.TABLE_SCHEMA='[$DB_Name]';

View the CREATE TABLE statement

Run the following SQL statement to confirm the primary key fields through the table creation statement.

  1. show create table [$Table_Name];

Query the table schema

Run the following SQL statement to confirm the primary key field based on the table structure.

  1. desc [$Table_Name];