My database has a table called fruit
:
fruit
+-------------+
| id | name |
+ ----------- +
| 1 | apple |
| 2 | orange |
| 3 | banana |
| 4 | grape |
+-------------+
id
is the a primary key. I want to add entries to the table, but only if they don't exist already.
IF NOT EXISTS (SELECT name FROM fruit WHERE name = 'mango')
INSERT INTO fruit (name)
VALUES ('mango')
I use a SQL GUI app called Sequel Pro, and this query errors with the following:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF NOT EXISTS (SELECT name FROM fruit WHERE name = 'mango') INSERT INTO frui' at line 1
Something fishy may be going on. The query may be stopping at INSERT INTO frui
. Problem with the app? Or is my query wrong?
You'd have to use
ALTER TABLE fruit ADD UNIQUE (name)
and then use
INSERT IGNORE INTO fruit (name) VALUES ('mango')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With