Insert - where does not exist

I would like to insert an entry into the table if the entry does not already exist with this domain name. The following SQL should achieve this, but gets an error.

The reason I want to make the update in the first place is because I do some updates later in my code and first need to write to my table before doing all the updates.

Why am I getting an error in this mySQL query?

insert into domain (name) values ('domain.com.au') WHERE NOT EXISTS ( select name from domain where name = 'domain.com.au' ); 

Both queries work separately when working separately, but they do not work together.

+4
source share
3 answers

Let your database process it for you. Use a unique index on name , and your INSERT will fail if you try to insert a duplicate.

 CREATE UNIQUE INDEX idx_name ON domain (name) 
+6
source

You cannot combine WHERE with an INSERT WHERE . Use REPLACE INTO instead.

0
source

What error are you getting?

I assume that the choice inside "where does not exist" is not allowed.

0
source

All Articles