MYSQL SQL SERVER

SQL – How to ‘insert if not exists’ in MySQL

How to write INSERT IF NOT EXISTS queries in standard SQL

If necessary, INSERT IF NOT EXISTS queries can be written in a single atomic statement, eliminating the need for a transaction, and without violating standards.
In this article we explained several ways to write such queries in a platform-independent way.

Several solutions:

One solution is to use a mutex table

Sql Code
insert into urls(url)
select '/blog/'
from mutex
    left outer join urls
        on urls.url = '/blog/'
where mutex.i = 1 and urls.url is null;

There are more flexible variations on this technique. Suppose there is no unique index on the url column.

If desired, it is possible to insert several values in a single statement by changing the WHERE clause:

Sql Code
insert into urls(url)
select '/blog/'
from mutex
    left outer join urls
        on urls.url = '/blog/'
where mutex.i < 5 and urls.url is null;

Now suppose the requirements specify up to three duplicate entries in the table, and each insert should add a single row.

It is possible to insert a row at a time while enforcing the requirement with the following query:

Sql Code
insert into urls(url)
select '/blog/'
from mutex
    left outer join urls
        on urls.url = '/blog/'
where mutex.i = 1
group by urls.url
having count(*) < 3;

This query shows the input to the INSERT statement:

Sql Code
select '/blog/', count(*)
from mutex
    left outer join urls
        on urls.url = '/blog/'
where mutex.i = 1
group by urls.url;

To start: as of the latest MySQL, syntax presented in the title is not possible. But there are several very easy ways to accomplish what is expected using existing functionality.

Another 3 possible solutions:
INSERT IGNORE,
REPLACE,
INSERT … ON DUPLICATE KEY UPDATE.

Below we’ll examine the three different methods and explain the pros and cons of each in turn.

See also  What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN

so you have a firm grasp on how to configure your own statements when providing new or potentially existing data for INSERTION.

Using INSERT IGNORE:

Using INSERT IGNORE effectively causes MySQL to ignore execution errors while attempting to perform INSERT statements.

This means that an INSERT IGNORE statement which contains a duplicate value in a UNIQUE index or PRIMARY KEY field does not produce an error, but will instead simply ignore that particular INSERT command entirely.

The obvious purpose is to execute a large number of INSERT statements for a combination of data that is both already existing in the database as well as new data coming into the system.

For example, our books table might contain a few records already:

mysql> SELECT * FROM books LIMIT 3;

+—-+———————————————————————————————-

| id | title                                  | author                          |  year_published |

+—-+———————————————————————————————

|  1 | In Search of Lost Time   | Marcel Proust             |           1913           |

|  2 | Ulysses                          | James Joyce               |           1922           |

|  3 | Don Quixote                  | Miguel de Cervantes   |           1605           |

+—-+———————————————————————————————-

3 rows in set (0.00 sec)

If we have a large batch of new and existing data to INSERT and part of that data contains a matching value for the id field (which is a UNIQUE PRIMARY_KEY in the table), using a basic INSERT will produce an expected error:

Sql Code
mysql> INSERT INTO books
    (id, title, author, year_published)
VALUES
    (1, 'Green Eggs and Ham', 'Dr. Seuss', 1960);
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'

On the other hand, if we use INSERT IGNORE, the duplication attempt is ignored and no resulting errors occur:

Sql Code
mysql> INSERT IGNORE INTO books
    (id, title, author, year_published)
VALUES
    (1, 'Green Eggs and Ham', 'Dr. Seuss', 1960);
Query OK, 0 rows affected (0.00 sec)

Using REPLACE

See also  [Solved-9 Answers] How to get a list of MySQL user accounts

In the event that you wish to actually replace rows where INSERT commands would produce errors due to duplicate UNIQUE or PRIMARY KEY values as outlined above, one option is to opt for the REPLACE statement.

When issuing a REPLACE statement, there are two possible outcomes for each issued command:

No existing data row is found with matching values and thus a standard INSERT statement is performed.

A matching data row is found, causing that existing row to be deleted with the standard DELETE statement, then a normal INSERT is performed afterward.

For example,
we can use REPLACE to swap out our existing record of id = 1 of In Search of Lost Time by Marcel Proust with Green Eggs and Ham by Dr. Seuss:

Sql Code
mysql> REPLACE INTO books
    (id, title, author, year_published)
VALUES
    (1, 'Green Eggs and Ham', 'Dr. Seuss', 1960);
Query OK, 2 rows affected (0.00 sec)

Notice that even though we only altered one row, the result indicates that two rows were affected because, we actually DELETED the existing row then INSERTED the new row to replace it.

Using INSERT … ON DUPLICATE KEY UPDATE

The alternative (and generally preferred) method for INSERTING into rows that may contain duplicate UNIQUE or PRIMARY KEY values is to use the INSERT … ON DUPLICATE KEY UPDATE statement and clause.

Unlike REPLACE – an inherently destructive command due to the DELETE commands it performs when necessary – using INSERT … ON DUPLICATE KEY UPDATE is non-destructive, in that it will only ever issue INSERT or UPDATE statements, but never DELETE.

See also  [ Solved -3 Answers] mysql installation problem

For example,
we have decided we wish to replace our id = 1 record of Green Eggs and Ham and revert it back to the original In Search of Lost Time record instead.

We can therefore take our original INSERT statement and add the new ON DUPLICATE KEY UPDATE clause:

Sql Code
mysql> SET @id = 1,
    @title = 'In Search of Lost Time',
    @author = 'Marcel Proust',
    @year_published = 1913;
INSERT INTO books
    (id, title, author, year_published)
VALUES
    (@id, @title, @author, @year_published)
ON DUPLICATE KEY UPDATE
    title = @title,
    author = @author,
    year_published = @year_published;

Notice that we’re using normal UPDATE syntax (but excluding the unnecessary table name and SET keyword), and only assigning the non-UNIQUE values.

Also, although unnecessary for the ON DUPLICATE KEY UPDATE method to function properly, we’ve also opted to utilize user variables so we don’t need to specify the actual values we want to INSERT or UPDATE more than once.

As a result, our id = 1 record was properly UPDATED as expected:

mysql> SELECT * FROM books LIMIT 1;

+—-+——————————–+———————+———————+

| id | title                                   | author              | year_published |

+—-+——————————–+——————–+———————-+

|  1 | In Search of Lost Time   | Marcel Proust |           1913          |

+—-+——————————–+——————–+———————–+

1 row in set (0.00 sec)

About the author

author

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment

X