Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query for a primary key in oracle 11g

Tags:

sql

oracle11g

Does anybody know how to query for a primary key of a table in Oracle 11g? I saw a similar question for SQL Server, but I've had no luck from trying the answers on that thread.

Thanks!

like image 600
web_novice118 Avatar asked Mar 18 '11 14:03

web_novice118


People also ask

How do I find the primary key in Oracle?

Answer: You can retrieve primary key information with the following SQL statement: SELECT cols. table_name, cols. column_name, cols.

How do I find primary key in schema?

In the Available Schemas pane, expand the tree to display your parent table's columns. Right click on the column that you want to designate as your new primary key; then, select Mark As Primary Key.

What is primary key in SQL query?

The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain UNIQUE values, and cannot contain NULL values. A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).


2 Answers

As the user that owns the table you can do:

select constraint_name, status, deferrable, deferred, validated, generated 
from user_constraints 
where constraint_type = 'P' and table_name = 'Table Name'

Update: I think this gets you what you need.

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

You can check this site for more details.

like image 174
Jacob Schoen Avatar answered Sep 28 '22 10:09

Jacob Schoen


SELECT cols.table_name
  ||' - '
  ||cols.column_name primary_key
FROM all_constraints cons,
  all_cons_columns cols,
  user_tables ut
WHERE cons.constraint_type = 'P'
AND cons.constraint_name   = cols.constraint_name
AND cons.owner             = cols.owner
AND cols.table_name        = ut.table_name
ORDER BY cols.table_name;
like image 28
Mandeep Singh Gill Avatar answered Sep 28 '22 10:09

Mandeep Singh Gill