mysql insert if not exists – 3 Ways To INSERT If Row Does Not Exist (UPSERT) in MySQL

mysql insert if not exists Using INSERT IGNORE. In this Best web development Article i will get knowledge on how to use mysql insert query for checking data already inserted or not.

mysql insert if not exists

Learn how to INSERT an If Row Does Not Exist (UPSERT) in MySQL. we will try to insert records and check if it EXISTS or not. However, you may use INSERT IGNORE if in your targer table you define any uniq_id or second_uniq_clm as unique keys.
How to INSERT If Row Does Not Exist (UPSERT) in MySQL?

Using INSERT IGNORE

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

mysql> SELECT * FROM members LIMIT 3;
+----+-------------------------+---------------------+----------------+
| id | title                   | team_manager        | finally_dt |
+----+-------------------------+---------------------+----------------+
|  1 | In Pakain of Kavi Devi  | Kevals Dharma       |           2022 |
|  2 | Ulysses                 | James Joyce         |           1922 |
|  3 | Don Quixote             | Miguel de Cervantes |           1605 |
+----+-------------------------+---------------------+----------------+
3 rows in set (0.00 sec)
mysql insert if not exists else update
mysql insert if not exists else update
mysql> INSERT INTO members
    (id, title, team_manager, finally_dt)
VALUES
    (1, 'Pakil Dogs and Majedar', 'Dr. Ravi', 2021);
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'

we use INSERT IGNORE

mysql> INSERT IGNORE INTO members
    (id, title, team_manager, finally_dt)
VALUES
    (1, 'Pakil Dogs and Majedar', 'Dr. Ravi', 2021);
Query OK, 0 rows affected (0.00 sec)

Using REPLACE

mysql> REPLACE INTO members
    (id, title, team_manager, finally_dt)
VALUES
    (1, 'Pakil Dogs and Majedar', 'Dr. Ravi', 2021);
Query OK, 2 rows affected (0.00 sec)

Don’t Miss : mysql insert if not exists else update

Using INSERT … ON DUPLICATE KEY UPDATE

mysql> SET @id = 1,
    @title = 'In Pakain of Kavi Devi',
    @team_manager = 'Kevals Dharma',
    @finally_dt = 2022;
INSERT INTO members
    (id, title, team_manager, finally_dt)
VALUES
    (@id, @title, @team_manager, @finally_dt)
ON DUPLICATE KEY UPDATE
    title = @title,
    team_manager = @team_manager,
    finally_dt = @finally_dt;
mysql> SELECT * FROM members LIMIT 1;
+----+------------------------+---------------+----------------+
| id | title                  | team_manager  | finally_dt 	   |
+----+------------------------+---------------+----------------+
|  1 | In Pakain of Kavi Devi | Kevals Dharma |           2022 |
+----+------------------------+---------------+----------------+
1 row in set (0.00 sec)

I hope you get an idea about mysql insert if not exists.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment