101

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?

Anonymous
  • 835
  • 1
  • 5
  • 21
Martti Laine
  • 12,655
  • 22
  • 68
  • 102

14 Answers14

164

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.

alexn
  • 57,867
  • 14
  • 111
  • 145
40

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';
Svetlozar Angelov
  • 21,214
  • 6
  • 62
  • 67
  • 4
    yes - this is one way. In the MySQL case, you can even simplify this, because the constraint_name will always be `PRIMARY` – Roland Bouman Feb 26 '10 at 11:53
  • wouldnt recommend this at all it's very resource requiring alexn's answer is far faster – Breezer Nov 02 '10 at 13:20
  • yeah, this query takes long time. what i did is another table with table names and table ids and trying to fetch from there, if it can't find the table, so it makes this long query and add it to the new table, works much faster. but alexn answer seems to be really good too – Shir Gans Feb 22 '11 at 09:00
  • 2
    But this solution works great when dealing with multiple tables. (Just select k.table_name, k.column_name, k.ordinal_position). – Claus Jul 24 '14 at 14:37
24
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
Christian
  • 27,509
  • 17
  • 111
  • 155
Roland Bouman
  • 31,125
  • 6
  • 66
  • 67
  • 1
    Just an FYI, on **sqlserver**, `constraint_name` looks like `UK_entity_name`, `PK_Users`, `FK_Users_Contacts` etc., so it doesn't seem it can be trusted to have a well known platform-agnostic value. – Christian Oct 05 '20 at 20:40
  • 1
    Whoa! I didn't expect you to update it. Other than a few things, it works perfectly! (I updated your answer for you with the fixes, hope you don't mind) – Christian Oct 06 '20 at 16:37
  • @Christian thanks fort the quick follow up and correction. much obliged! – Roland Bouman Oct 08 '20 at 06:42
  • for me this was not working on an older mysql 5.5, changed to this one `SELECT kcu.column_name, kcu.ordinal_position FROM information_schema.table_constraints tc INNER JOIN information_schema.key_column_usage kcu ON tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA AND tc.TABLE_NAME = kcu.TABLE_NAME 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 = 'logins' -- specify your table. ORDER BY kcu.ordinal_position` – detzu Jan 30 '21 at 23:11
  • Need to add `AND tc.TABLE_NAME = kcu.TABLE_NAME` above `WHERE` – bjc Apr 09 '21 at 18:01
11

use:

show columns from tablename where `Key` = "PRI";
v1rus32
  • 109
  • 1
  • 4
  • This works best for me since I don't have to access the Information Schema (which is not available) and I can dynamically pick up the keys from the field column. – Betty Mock Jun 15 '21 at 13:32
10

How about this:

SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'Your Database'
  AND TABLE_NAME = 'Your Table name'
  AND COLUMN_KEY = 'PRI';


SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'Your Database'
  AND TABLE_NAME = 'Your Table name'
  AND COLUMN_KEY = 'UNI';
Alex
  • 1,457
  • 1
  • 13
  • 26
Afroz
  • 1,017
  • 2
  • 12
  • 24
7

If you want to generate the list of primary keys dynamically via PHP in one go without having to run through each table you can use

SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.key_column_usage 
WHERE table_schema = '$database_name' AND CONSTRAINT_NAME = 'PRIMARY' 

though you do need to have access to the information.schema to do this.

Alex
  • 1,457
  • 1
  • 13
  • 26
Donal
  • 71
  • 1
  • 1
3

Shortest possible code seems to be something like

// $dblink contain database login details 
// $tblName the current table name 
$r = mysqli_fetch_assoc(mysqli_query($dblink, "SHOW KEYS FROM $tblName WHERE Key_name = 'PRIMARY'")); 
$iColName = $r['Column_name']; 
K. Kilian Lindberg
  • 2,918
  • 23
  • 30
2

For a PHP approach, you can use mysql_field_flags

$q = mysql_query('select * from table limit 1');

for($i = 0; $i < mysql_num_fields(); $i++)
    if(strpos(mysql_field_tags($q, $i), 'primary_key') !== false)
        echo mysql_field_name($q, $i)." is a primary key\n";
Benoît Vidis
  • 3,908
  • 2
  • 23
  • 24
2

I've got it, finally!

<?php

function mysql_get_prim_key($table){
    $sql = "SHOW INDEX FROM $table WHERE Key_name = 'PRIMARY'";
    $gp = mysql_query($sql);
    $cgp = mysql_num_rows($gp);

    if ($cgp > 0) {
        // Note I'm not using a while loop because I never use more than one prim key column
        $agp = mysql_fetch_array($gp);
        extract($agp);
        
        return($Column_name);
    } else {
        return(false);
    }
}

?>
Linus Unnebäck
  • 23,234
  • 15
  • 74
  • 89
John
  • 976
  • 1
  • 15
  • 21
0

I use SHOW INDEX FROM table ; it gives me alot of informations ; if the key is unique, its sequenece in the index, the collation, sub part, if null, its type and comment if exists, see screenshot herehere

  • Could you please elaborate more your answer adding a little more description about the solution you provide? – abarisone Apr 10 '15 at 11:39
0

MySQL has a SQL query "SHOW INDEX FROM" which returns the indexes from a table. For eg. - the following query will show all the indexes for the products table:-

SHOW INDEXES FROM products \G

It returns a table with type, column_name, Key_name, etc. and displays output with all indexes and primary keys as -

*************************** 1. row ***************************
        Table: products
   Non_unique: 0
     Key_name: PRIMARY
 Seq_in_index: 1
  Column_name: product_id
    Collation: A
  Cardinality: 0
     Sub_part: NULL
       Packed: NULL
         Null: 
   Index_type: BTREE
      Comment: 
Index_comment: 

To just display primary key from the table use :-

SHOW INDEXES FROM table_name WHERE Key_name = 'PRIMARY'
0

If you have spatial tables in your database, use:

SHOW KEYS FROM table WHERE Key_name = 'PRIMARY' OR Key_name = 'OGR_FID'
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
AndyT
  • 31
  • 2
0

You should use PRIMARY from key_column_usage.constraint_name = "PRIMARY"

sample query,

SELECT k.column_name as PK, concat(tbl.TABLE_SCHEMA, '.`', tbl.TABLE_NAME, '`') as TABLE_NAME
FROM information_schema.TABLES tbl
JOIN information_schema.key_column_usage k on k.table_name = tbl.table_name
WHERE k.constraint_name='PRIMARY'
  AND tbl.table_schema='MYDB'
  AND tbl.table_type="BASE TABLE";
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
0
SELECT k.column_name
FROM information_schema.key_column_usage k   
WHERE k.table_name = 'YOUR TABLE NAME' AND k.constraint_name LIKE 'pk%'

I would recommend you to watch all the fields

Satish Patro
  • 3,645
  • 2
  • 27
  • 53