Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get primary key of table?

Is there a way to get the name of primary key field from mysql-database? For example:

I have a table like this:

+----+------+ | id | name | +----+------+ | 1  | Foo1 | | 2  | Foo2 | | 3  | Foo3 | +----+------+ 

Where the field id is primary key (it has auto increment but I can't use that). How can I retrieve fields name "id" in php?

like image 615
Martti Laine Avatar asked Feb 26 '10 11:02

Martti Laine


People also ask

What is the primary key of a table in SQL?

A primary key is a field in a table which uniquely identifies each row/record in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values.

How do you check if a table has a primary key in SQL Server?

Show activity on this post. So SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA. TABLES WHERE TABLE_NAME IN ('TableA','TableB','TableC') EXCEPT SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA. TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' ?


1 Answers

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.

like image 98
alexn Avatar answered Sep 28 '22 05:09

alexn