Question

I'm trying to add a value to a table but not without checking if the value already exists. This is what I have so far:

IF NOT EXISTS (
   SELECT series.seriesName 
   FROM series 
   WHERE series.seriesName='Avengers'
) 
BEGIN 
   INSERT INTO series (seriesName) VALUES 'Avengers' 
END;

Database is a MySQL db on Ubuntu

Was it helpful?

Solution

You can use IGNORE keyword here.

It could look like:

INSERT IGNORE INTO series (seriesName) VALUES 'Avengers'

The important thing is to create a unique key on seriesName field as it seems that you want it to be unique. INSERT IGNORE doesn't make the insert when key value already exists.

If you would like to be able to get id (primary key value) for row that wasn't inserted (already existed), you can do the following trick:

INSERT IGNORE INTO series (seriesName) VALUES 'Avengers'
    ON DUPLICATE KEY UPDATE seriesID= LAST_INSERT_ID(seriesID) 

Then you will be able to get the ID with LAST_INSERT_ID() function no matter if the row was inserted or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top