Amy Neville
Amy Neville

Reputation: 10581

Avoid inserting duplicate column values

I have a very simple table with 3 columns tag_id, label, timestamp and I need as lightweight as possible a query to insert only when there is a new value for the column label.

How would I write an sql query to do this? I can see some examples already on the site but they are all mixed up in more complex queries (some involving subqueries) that I can't understand.

There seems to be different ways of doing it and I need to find out the most lightweight one so that I can repeat it in a loop to insert multiple tags in one go without putting too much strain on the server.

Upvotes: 1

Views: 1149

Answers (2)

Nono
Nono

Reputation: 7302

you can also use:

INSERT INTO table(`label`) VALUES ("new value") 
 ON DUPLICATE KEY UPDATE `label` = "new value";

Upvotes: -1

Explosion Pills
Explosion Pills

Reputation: 191729

You can use

ALTER TABLE `tableName` ADD UNIQUE KEY (label);

This will enforce a unique value for that column in the schema. You will get an error when you attempt to insert a duplicate value. If you want to simply ignore the error, you can use INSERT IGNORE INTO.

Upvotes: 3

Related Questions