Skip to content
Advertisement

SQL query to find Primary Key of a table?

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement