How to get primary key column in Oracle?

I need to get the primary key column name.

At the input, I have only the table name.

+66
oracle
Jan 26 '12 at 10:14
source share
5 answers
SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = 'TABLE_NAME' AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner ORDER BY cols.table_name, cols.position; 

Make sure "TABLE_NAME" is uppercase, as Oracle stores table names in uppercase.

+116
Jan 26 '12 at 10:26
source share

Same as the answer from Richie, but a bit more concise.

  • Request for custom restrictions only

     SELECT column_name FROM all_cons_columns WHERE constraint_name = ( SELECT constraint_name FROM user_constraints WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P' ); 
  • Request for all restrictions

     SELECT column_name FROM all_cons_columns WHERE constraint_name = ( SELECT constraint_name FROM all_constraints WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P' ); 
+8
Sep 22 '14 at 13:01
source share
 Select constraint_name,constraint_type from user_constraints where table_name** **= 'TABLE_NAME' ; 

(The primary key will be listed here, and then)

 Select column_name,position from user_cons_cloumns where constraint_name='PK_XYZ'; 

(This will give you a column, here PK_XYZ is the name of the primay key)

+1
Apr 25 '13 at 14:00
source share

Save the following script as something like findPK.sql.

 set verify off accept TABLE_NAME char prompt 'Table name>' SELECT cols.column_name FROM all_constraints cons NATURAL JOIN all_cons_columns cols WHERE cons.constraint_type = 'P' AND table_name = UPPER('&TABLE_NAME'); 

Then it can be called using

 @findPK 
0
Sep 09 '15 at 3:42
source share

Try this code. Here I created a table to get the primary key column in oracle called test, and then it asks

 create table test ( id int, name varchar2(20), city varchar2(20), phone int, constraint pk_id_name_city primary key (id,name,city) ); SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = 'TEST' AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner ORDER BY cols.table_name, cols.position; 
0
May 24 '17 at 11:22
source share



All Articles