I am implementing a search functionality from UI for this I want to give a drop down of column names which have unique constraints along with any primary key column if present, so user can search with any of these selected column relate data. I have searched for such query but haven't found
Something like:
SELECT COLUMN_NAMEs FROM TABLE WHERE CONSTRAINTS UNIQUE OR PRIMARY
Is there any query to achieve this ...
To check for a unique constraint use the already provided method: select count(*) cnt from user_constraints uc where uc. table_name='YOUR_TABLE_NAME' and uc.
Use the view table_constraints in the information_schema schema. The column table_name gives you the name of the table in which the constraint is defined, and the column constraint_name contains the name of the constraint.
The syntax for enabling a unique constraint in Oracle is: ALTER TABLE table_name ENABLE CONSTRAINT constraint_name; table_name.
To define a UNIQUE constraint, you use the UNIQUE keyword followed by one or more columns. You can define a UNIQUE constraint at the column or the table level. Only at the table level, you can define a UNIQUE constraint across multiple columns.
USER_CONSTRAINTS would return foreign keys also. You need only primary and unique keys. But uniqueness can be achieved via unique index too. It won't be shown in constraints list. You need to watch USER_INDEXES view. The good point is that primary and unique keys create corresponding unique indexes. So, it's necessary and sufficient to check USER_INDEXES.
UPD: see Lalit Kumar B's comment.
select c.COLUMN_NAME
from USER_INDEXES i, USER_IND_COLUMNS c
where i.TABLE_NAME = 'YOUR_TABLE'
and i.UNIQUENESS = 'UNIQUE'
and i.TABLE_NAME = c.TABLE_NAME
and i.INDEX_NAME = c.INDEX_NAME
union
select cc.COLUMN_NAME
from USER_CONSTRAINTS con, USER_CONS_COLUMNS cc
where con.TABLE_NAME = 'YOUR_TABLE'
and con.CONSTRAINT_TYPE in ( 'U', 'P' )
and con.TABLE_NAME = cc.TABLE_NAME
and con.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With