0

I need to add a row to a MySQL database table but only if the row doesn't already exist. My database server just went down so I can't test this, but will this work as expected?

INSERT INTO `blocks` (`block_file`,`settings_group`)
VALUES ('announcements','announcement_settings')
WHERE NOT EXISTS (SELECT `block_file`,`settings_group`
                  FROM `blocks`
                  WHERE `block_file`='announcements' AND `settings_group`='announcement_settings')

It seems like sound logic. Is this a valid query or is there a better way of doing this?

2
  • In SQL Server that type of approach would give you a race condition. Not sure whether this is true for MySQL as well. Is it just this specific query or do you always want to enforce uniqueness on those 2 columns? Commented Feb 8, 2011 at 23:26
  • 1
    Same with mysql - you cannot modify a table while you are selecting from it Commented Feb 8, 2011 at 23:34

1 Answer 1

3

Just create UNIQUE index on (block_file,settings_group) columns, and MySQL will never let you insert a row that would duplicate these values.

And to answer the question: No, it will not work at all.

Sign up to request clarification or add additional context in comments.

2 Comments

And if you need to insert several records, just use the IGNORE keyword, so if you try to insert a duplicate row, the error would be treated as warning. Check the sintax dev.mysql.com/doc/refman/5.0/es/insert.html
Thanks! Works just as expected and much cleaner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.