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?
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');
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.
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.
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.
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'
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