Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make "No Duplicates" column in SQL Server 2008?

I have a simple table in my SQL Server database. This table contains two columns: ID int, Name nvarchar(50). The ID column is the primary key for my table.

I want the "Name" column to be "(No Duplicates)", like in Microsoft Access, But this column isn't the primary column. How could I do this?

like image 302
Wahid Bitar Avatar asked Oct 19 '09 14:10

Wahid Bitar


People also ask

How can I delete duplicate records in SQL Server 2008?

To delete the duplicate rows from the table in SQL Server, you follow these steps: Find duplicate rows using GROUP BY clause or ROW_NUMBER() function. Use DELETE statement to remove the duplicate rows.

How exclude duplicates in SQL Server?

The SQL DISTINCT keyword, which we have already discussed is used in conjunction with the SELECT statement to eliminate all the duplicate records and by fetching only the unique records.

How do I remove duplicates from one column in SQL?

How to Eliminate Duplicate Values Based on Only One Column of the Table in SQL? In SQL, some rows contain duplicate entries in a column. For deleting such rows, we need to use the DELETE keyword along with self-joining the table with itself.


2 Answers

Add a unique constraint for that column:

ALTER TABLE Foo ADD CONSTRAINT UQ_Name UNIQUE (Name) 

To add it through SQL Management Studio UI:

  1. Open SQL Server Management Studio.
  2. Expand the Tables folder of the database where you wish to create the constraint.
  3. Right-click the table where you wish to add the constraint and click Design.
  4. In Table Designer, click on Indexes/Keys.
  5. Click Add.
  6. Choose Unique Key in the Type drop-down list.

To handle a situation where a unique constraint violation occurs, see for error 2601.

like image 106
Anton Gogolev Avatar answered Oct 17 '22 05:10

Anton Gogolev


This can also be done another way with the SSMS GUI if you prefer:

  1. Right click "Indexes" under your table in the SSMS Solution Explorer and click "New Index..." (I know you are looking to create a contstraint, not an index, but this is exactly what the ADD CONSTRAINT SQL script does.

enter image description here

  1. Give new index a name (e.g. "UQ_MyUniqueColumn"), check "Unique", and click "Add..."

enter image description here

  1. Check your column in the next window

enter image description here

  1. Click OK in both windows
like image 39
Tony L. Avatar answered Oct 17 '22 05:10

Tony L.