tags:

views:

27

answers:

2

This is what I'm doing right now (name is UNIQUE):

SELECT * FROM fruits WHERE name='apple';

Check if the query returned any result. If yes, don't do anything. If no, a new value has to be inserted:

INSERT INTO fruits (name) VALUES ('apple');

Instead of the above is it ok to insert the value into the table without checking if it already exists? If the name already exists in the table, an error will be thrown and if it doesn't, a new record will be inserted.

Right now I am having to insert 500 records in a for loop, which results in 1000 queries. Will it be ok to skip the "already-exists" check?

+4  A: 

You can use the IGNORE feature:

INSERT IGNORE INTO fruits VALUES ('apple')

If there is a key violation, it just skips this value

simendsjo
+2  A: 

check out

INSERT IGNORE INTO ...

and

INSERT ON DUPLICATE KEY UPDATE ...

Thes second method is preferred as the IGNORE statement simply causes mysql to issue warning instead of error

Gunjan
The second method is *not* preferred as OP wants a duplicate entry to be skipped, not updated.
BoltClock
yeah but it can easily be updated to itself as set `apple` = `apple`
Gunjan