How to get primary key of table?

A better way is to use SHOW KEYS since you don't always have access to information_schema. The following works:

SHOW KEYS FROM table WHERE Key_name = 'PRIMARY'

Column_name will contain the name of the primary key.


SELECT kcu.column_name, kcu.ordinal_position
FROM   information_schema.table_constraints tc
INNER JOIN information_schema.key_column_usage kcu
ON     tc.CONSTRAINT_CATALOG = kcu.CONSTRAINT_CATALOG
AND    tc.CONSTRAINT_SCHEMA = kcu.CONSTRAINT_SCHEMA
AND    tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
WHERE  tc.table_schema = schema()             -- only look in the current schema
AND    tc.constraint_type = 'PRIMARY KEY'
AND    tc.table_name = '<your-table-name>'    -- specify your table.
ORDER BY kcu.ordinal_position

Here is the Primary key Column Name

SELECT k.column_name
FROM information_schema.table_constraints t
JOIN information_schema.key_column_usage k
USING(constraint_name,table_schema,table_name)
WHERE t.constraint_type='PRIMARY KEY'
  AND t.table_schema='YourDatabase'
  AND t.table_name='YourTable';