I have a table setup with a UNIQUE column called, for example, test. I want to insert a row with the column test only if there isn't already a row in the table with test. I know I could just do the INSERT query and it would throw up an error if it already existed (and wouldn't really cause any harm AFAIK), but is there a way to do this properly using only MySQL? I'm pretty sure it can be done with functions but I've never used those before and I think there's an easier way.
4 Answers
Sounds like a job for INSERT IGNORE:
If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.
3 Comments
You can use the IGNORE keyword, like this:
INSERT IGNORE INTO table_name (test) VALUES('my_value');
From the MySQL documentation:
If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.
If you want to update the existing row rather than ignore the duplicate update entirely, check out the ON DUPLICATE KEY UPDATE syntax.