Nastro
Nastro

Reputation: 1769

How to make unique combination of columns values?

I have a table with data like this:

id |  link  |  name  | date 
 1     aa      bob      1
 1     aa      tom      2
 1     bb      tom      3
 2     cc      lora     4

It means I can have not unique values in any column but I CAN'T have the same row with identical id link name (date doesn't matter). This is the example what I can't have:

 id |  link  |  name  |  date 
  1     aa       bob      1
  1     aa       bob      2

I tried to:

ALTER TABLE table ADD UNIQUE KEY `uk_id_link_name` (id, link, name);

also:

ALTER TABLE `table` ADD UNIQUE `unique_index`(`id`, `link`, `name`);

But it gives me an error:

Duplicate entry

How to make unique rows (combination of columns values which is not unique)?

EDIT: I don't want to delete duplicates from table.

Upvotes: 0

Views: 1464

Answers (2)

Jortx
Jortx

Reputation: 727

The correct syntax for SQL Server should be the next:

ALTER TABLE TableName ADD CONSTRAINT ConstraintName UNIQUE (id, link, name)

But before create the constraint, of course you should ensure that there are not existing rows braking the constraint, for example using this query:

SELECT id, link, name, COUNT(*)
FROM TableName
GROUP BY id, link, name
HAVING COUNT(*) >= 2

This query returns the duplicates grouping by the three fields: id, link, name

If the query returns rows, you have to solve these duplicates before create the unique constraint.

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1270873

Your table already violates the unique constraint. So you need to get rid of the offending values.

You can delete all but the earliest date:

delete t
    from t join
         (select id, link, name, min(date) as mindate
          from t
          group by id, link, name
         ) tt
         using (id, link, name)
    where date > mindate;

When the data is compatible, you can add the unique constraint.

Note: back up/make a copy of the table before doing this, so you don't lose data that you might really need.

Upvotes: 2

Related Questions