Check if column of a table has unique constraint

11,343

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'
Share:
11,343

Related videos on Youtube

Dhwani
Author by

Dhwani

Software Engineer, India.

Updated on September 15, 2022

Comments

  • Dhwani
    Dhwani over 1 year

    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?