Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only insert into table if item does not exist [duplicate]

Tags:

sql

mysql

insert

My database has a table called fruit:

Table 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.

The query

IF NOT EXISTS (SELECT name FROM fruit WHERE name = 'mango')
INSERT INTO fruit (name) 
VALUES ('mango')

Error

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

Perhaps

Something fishy may be going on. The query may be stopping at INSERT INTO frui. Problem with the app? Or is my query wrong?

like image 280
izolate Avatar asked Jan 04 '14 23:01

izolate


1 Answers

You'd have to use

ALTER TABLE fruit ADD UNIQUE (name) 

and then use

INSERT IGNORE INTO fruit (name) VALUES ('mango')
like image 188
ShiningLight Avatar answered Oct 16 '22 03:10

ShiningLight