Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if column of a table has unique constraint

Tags:

sql

sql-server

I need a query which can tell me if a column of a table has unique constraint or not. If doesn't have, I have to add unique constraint. Currently I am using below query to check if a table's column has unique constraint or not:

IF NOT EXISTS (SELECT *
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
    WHERE TC.CONSTRAINT_TYPE = 'UNIQUE' AND CONSTRAINT_NAME = 'IX_Product_Users' AND TABLE_NAME = 'Product_Users')
BEGIN
    ALTER TABLE Product_Users
    ADD CONSTRAINT IX_Product_Users UNIQUE (EmpID)
END
GO

Tried this one too, but it is not able to check on which column the constraint it is:

SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME='Product_Users' AND CONSTRAINT_TYPE = 'UNIQUE'

But I think this is a wrong way cause there might be possibility that unique constraint name is different. Is there any precise way to do this?

like image 330
Dhwani Avatar asked Jan 03 '15 05:01

Dhwani


People also ask

How do you find the unique constraint in a table?

select * from all_ind_columns where index_name='SYSC001401'; You can view the restrictions on an Oracle table by examining the dba_cons_columns system table. e.g. (select constraint_name from dba_constraints where table_name = 'REPORTER_JOURNAL');

How can check column constraint in SQL Server?

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.

How do I find unique constraints in SQL Server?

You can create a unique constraint in SQL Server by using SQL Server Management Studio or Transact-SQL to ensure no duplicate values are entered in specific columns that do not participate in a primary key.

How do I find column constraints?

The CHECK constraint is used to limit the value range that can be placed in a column. If you define a CHECK constraint on a column it will allow only certain values for this column. If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.


1 Answers

Rather than using the constraint name look for the same definition. something like

SELECT * 
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc 
    inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cu 
        on cu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME 
where 
    tc.CONSTRAINT_TYPE = 'UNIQUE'
    and tc.TABLE_NAME = 'Product_Users'
    and cu.COLUMN_NAME = 'EmpID'
like image 195
G B Avatar answered Sep 22 '22 20:09

G B