SQL query to find Primary Key of a table?

前端 未结 8 443
耶瑟儿~
耶瑟儿~ 2021-02-04 01:30

How can I find which column is the primary key of a table by using a query?

相关标签:
8条回答
  • 2021-02-04 01:57

    Try this query in SQL server:

    SELECT     X.NAME AS INDEXNAME,
               COL_NAME(IC.OBJECT_ID,IC.COLUMN_ID) AS COLUMNNAME
    FROM       SYS.INDEXES  X 
    INNER JOIN SYS.INDEX_COLUMNS  IC 
            ON X.OBJECT_ID = IC.OBJECT_ID
           AND X.INDEX_ID = IC.INDEX_ID
    WHERE      X.IS_PRIMARY_KEY = 1
      AND      OBJECT_NAME(IC.OBJECT_ID)='YOUR_TABLE'
    
    0 讨论(0)
  • 2021-02-04 02:01

    This is a duplicate question:

    credit to Lukmdo for this answer:

    It might be not advised but works just fine:

    show index from TABLE where Key_name = 'PRIMARY' ;
    

    The solid way is to use information_schema:

    SELECT k.COLUMN_NAME
    FROM information_schema.table_constraints t
    LEFT JOIN information_schema.key_column_usage k
    USING(constraint_name,table_schema,table_name)
    WHERE t.constraint_type='PRIMARY KEY'
        AND t.table_schema=DATABASE()
        AND t.table_name='owalog';
    
    0 讨论(0)
提交回复
热议问题