SQL query to find Primary Key of a table?

前端 未结 8 442
耶瑟儿~
耶瑟儿~ 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:38

    For MSSQL: SELECT DISTINCT C.TABLE_NAME,C.COLUMN_NAME,C.DATA_TYPE FROM sys.indexes I INNER JOIN sys.index_columns IC ON I.OBJECT_ID = IC.OBJECT_ID AND I.INDEX_ID = IC.INDEX_ID INNER JOIN information_schema.columns C ON COL_NAME(IC.OBJECT_ID,IC.COLUMN_ID) = C.COLUMN_NAME WHERE I.IS_PRIMARY_KEY = 1

    0 讨论(0)
  • 2021-02-04 01:39

    LEFT joining table_constraints seems to take more time on mine. i use Information_schema.COLUMNS

    SELECT TABLE_SCHEMA , TABLE_NAME , COLUMN_NAME FROM Information_schema.Columns WHERE COLUMN_KEY = "PRI" AND TABLE_SCHEMA = DATABASE()

    0 讨论(0)
  • 2021-02-04 01:40

    For MySQL:

    SELECT GROUP_CONCAT(COLUMN_NAME), TABLE_NAME
    FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
    WHERE
      TABLE_SCHEMA = '**database name**'
      AND CONSTRAINT_NAME='PRIMARY'
    GROUP BY TABLE_NAME;
    

    Warning a primary key with two columns will have them separated by a coma (,)

    0 讨论(0)
  • 2021-02-04 01:50

    The following query gives the list of all the primary keys in the given database.

    SELECT DISTINCT TABLE_NAME ,column_name
        FROM INFORMATION_SCHEMA.key_column_usage
        WHERE TABLE_SCHEMA IN ('*your_db_name*');
    
    0 讨论(0)
  • 2021-02-04 01:53

    For Oracle, you can look it up in the ALL_CONSTRAINTS table:

    SELECT a.COLUMN_NAME
    FROM all_cons_columns a INNER JOIN all_constraints c 
         ON a.constraint_name = c.constraint_name 
    WHERE c.table_name = 'TBL'
      AND c.constraint_type = 'P';
    

    DEMO.

    For SQL Server, it was already answered here, and for MySQL check @ajon's answer.

    0 讨论(0)
  • 2021-02-04 01:56

    In mySQL

    SHOW COLUMNS FROM `table_name`;
    

    This show the details of the columns ie field, data-type, key etc.

    0 讨论(0)
提交回复
热议问题