This assumes that you have an UNIQUE INDEX or PRIMARY KEY on (pub_id ,paper_code )

INSERT INTO vendor_publication_daily_draws (`alouette.acct`, month, year, paper_code, pub_id, `01`) 
VALUES ('97', '08', '2022', 'STSC', '73609850', '5') 
  ON DUPLICATE KEY UPDATE month=VALUES(month),`alouette.acct` = VALUES(`alouette.acct`)
  ,year = VALUES(year),`01` = VALUES(`01`)

there is also the possibility of a dynamic approach, which i also can provide if abouve fails.

Answer from nbk on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ mariadb โ€บ how-to-insert-if-not-exists-in-mariadb
How to Insert if Not Exists in MariaDB - GeeksforGeeks
July 23, 2025 - MariaDB provides a powerful tool to handle this situation efficiently: the SQL IF NOT EXISTS clause. This clause allows us to perform an INSERT operation only if the record does not already exist, or an UPDATE operation if it does.
Discussions

sql - IF NOT EXISTS - Mariadb Syntax - Stack Overflow
I am using MariaDB. IF NOT EXISTS (SELECT * FROM valuation WHERE ticker = 'BK001EUR' AND depot_id =1 AND src_id =2 AND valuation_date ='2009-09-09') INSERT INTO valuation (ticker,depot_id,src_id,valuation_date,value) VALUES ('BK001EUR',1,2,'2009-09-09',14999260.46) ELSE UPDATE valuation SET ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
MySql Table Insert if not exist otherwise update - Stack Overflow
UPDATE AggregatedData SET datenum="734152.979166667", Timestamp="2010-01-14 23:30:00.000" WHERE datenum="734152.979166667"; It works if the datenum exists, but I want to insert this data as a new... More on stackoverflow.com
๐ŸŒ stackoverflow.com
sql - How can I do 'insert if not exists' in MySQL? - Stack Overflow
I started by googling and found the article How to write INSERT if NOT EXISTS queries in standard SQL which talks about mutex tables. I have a table with ~14 million records. If I want to add more ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
mysql - If exists then update else insert - Database Administrators Stack Exchange
I am trying to create a STORED PROCEDURE that will be used to UPDATE a table called machine. This table has three columns (machine_id, machine_name and reg_id). In aforementioned table,reg_id (INT... More on dba.stackexchange.com
๐ŸŒ dba.stackexchange.com
April 29, 2015
๐ŸŒ
Databasefaqs
databasefaqs.com โ€บ home โ€บ mariadb insert if not exists
MariaDB Insert If Not Exists - DatabaseFAQs.com
March 4, 2025 - In this query, with the help of the INSERT IGNORE statement, MariaDB will insert a row if the values do not exist in the table. It will also produce a warning about the PRIMARY KEY constraint for duplicate key values.
๐ŸŒ
TechOnTheNet
techonthenet.com โ€บ mariadb โ€บ exists.php
MariaDB: EXISTS Condition
Let's look at an example of how to use the EXISTS condition in the INSERT statement in MariaDB. ... INSERT INTO contacts (contact_id, contact_name) SELECT site_id, site_name FROM sites WHERE EXISTS (SELECT * FROM pages WHERE pages.site_id = sites.site_id); Let's look at an example of how to use the EXISTS condition in the UPDATE statement in MariaDB.
Top answer
1 of 12
1034

Use INSERT IGNORE INTO table.

There's also INSERT โ€ฆ ON DUPLICATE KEY UPDATE syntax, and you can find explanations in 13.2.6.2 INSERT ... ON DUPLICATE KEY UPDATE Statement.


Post from bogdan.org.ua according to Google's webcache:

18th October 2007

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.

There are 3 possible solutions: using INSERT IGNORE, REPLACE, or INSERT โ€ฆ ON DUPLICATE KEY UPDATE.

Imagine we have a table:

CREATE TABLE `transcripts` (
`ensembl_transcript_id` varchar(20) NOT NULL,
`transcript_chrom_start` int(10) unsigned NOT NULL,
`transcript_chrom_end` int(10) unsigned NOT NULL,
PRIMARY KEY (`ensembl_transcript_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now imagine that we have an automatic pipeline importing transcripts meta-data from Ensembl, and that due to various reasons the pipeline might be broken at any step of execution. Thus, we need to ensure two things:

  1. repeated executions of the pipeline will not destroy our > database
  1. repeated executions will not die due to โ€˜duplicate > primary keyโ€™ errors.

Method 1: using REPLACE

Itโ€™s very simple:

REPLACE INTO `transcripts`
SET `ensembl_transcript_id` = 'ENSORGT00000000001',
`transcript_chrom_start` = 12345,
`transcript_chrom_end` = 12678;

If the record exists, it will be overwritten; if it does not yet exist, it will be created. However, using this method isnโ€™t efficient for our case: we do not need to overwrite existing records, itโ€™s fine just to skip them.

Method 2: using INSERT IGNORE Also very simple:

INSERT IGNORE INTO `transcripts`
SET `ensembl_transcript_id` = 'ENSORGT00000000001',
`transcript_chrom_start` = 12345,
`transcript_chrom_end` = 12678;

Here, if the โ€˜ensembl_transcript_idโ€™ is already present in the database, it will be silently skipped (ignored). (To be more precise, hereโ€™s a quote from MySQL reference manual: โ€œIf you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted.โ€.) If the record doesnโ€™t yet exist, it will be created.

This second method has several potential weaknesses, including non-abortion of the query in case any other problem occurs (see the manual). Thus it should be used if previously tested without the IGNORE keyword.

Method 3: using INSERT โ€ฆ ON DUPLICATE KEY UPDATE:

Third option is to use INSERT โ€ฆ ON DUPLICATE KEY UPDATE syntax, and in the UPDATE part just do nothing do some meaningless (empty) operation, like calculating 0+0 (Geoffray suggests doing the id=id assignment for the MySQL optimization engine to ignore this operation). Advantage of this method is that it only ignores duplicate key events, and still aborts on other errors.

As a final notice: this post was inspired by Xaprb. Iโ€™d also advise to consult his other post on writing flexible SQL queries.

2 of 12
340

Solution:

INSERT INTO `table` (`value1`, `value2`) 
SELECT 'stuff for value1', 'stuff for value2' FROM DUAL 
WHERE NOT EXISTS (SELECT * FROM `table` 
      WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1) 

Explanation:

The innermost query

SELECT * FROM `table` 
      WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1

used as the WHERE NOT EXISTS-condition detects if there already exists a row with the data to be inserted. After one row of this kind is found, the query may stop, hence the LIMIT 1 (micro-optimization, may be omitted).

The intermediate query

SELECT 'stuff for value1', 'stuff for value2' FROM DUAL

represents the values to be inserted. DUAL refers to a special one row, one column table present by default in all Oracle databases (see https://en.wikipedia.org/wiki/DUAL_table). On a MySQL-Server version 5.7.26 I got a valid query when omitting FROM DUAL, but older versions (like 5.5.60) seem to require the FROM information. By using WHERE NOT EXISTS the intermediate query returns an empty result set if the innermost query found matching data.

The outer query

INSERT INTO `table` (`value1`, `value2`) 

inserts the data, if any is returned by the intermediate query.

Find elsewhere
๐ŸŒ
sebhastian
sebhastian.com โ€บ mysql-insert-if-not-exists
How to insert row if not exists in MySQL | sebhastian
March 21, 2023 - With the INSERT IGNORE statement, MySQL will insert a new row only if the value specified for the unique column doesnโ€™t already exist. The ON DUPLICATE KEY UPDATE clause allows you to update the row with new values when the value for the UNIQUE ...
๐ŸŒ
Stack Exchange
dba.stackexchange.com โ€บ questions โ€บ 286856 โ€บ mariadb-insert-records-list-of-tuples-into-table-if-not-exists
query - MariaDB: Insert records (list of tuples) into table if not exists - Database Administrators Stack Exchange
INSERT INTO `test` (col1, col2) SELECT * FROM (SELECT '1','2') AS tmp WHERE NOT EXISTS ( SELECT * FROM `test` WHERE col1='1' AND col2='2' ) LIMIT 1; INSERT INTO `test` (col1, col2) SELECT * FROM (SELECT '3','4') AS tmp WHERE NOT EXISTS ( SELECT ...
๐ŸŒ
Reddit
reddit.com โ€บ r/mysql โ€บ if exists update else insert (but only if a non primary key value duplicate is found)
r/mysql on Reddit: IF EXISTS update ELSE insert (BUT only if a non primary key value duplicate is found)
January 24, 2020 -

Hey everyone. It seems that MySql doesn't have the option of simply doing IF EXISTS clause right in the query unless you've already performing a select. On top of that the ON DUPLICATE KET clause only works with primary keys. If that's the case, who can I realize the following query in mysql

    IF EXISTS (SELECT * FROM subscriptions WHERE user_id = '$user_id' )
        BEGIN
            UPDATE subscriptions
            SET pp_agreement_id='47', status='active'
            WHERE user_id=$user_id 
        END
    ELSE
        BEGIN
            INSERT INTO subscriptions (user_id, pp_agreement_id, status)
            VALUES ('$user_id', '47', 'active')
        END

The thing here is that I'm not looking for duplicate primary keys. I'm looking for a custom column.

๐ŸŒ
GitHub
gist.github.com โ€บ bobcode99 โ€บ e071f72d3c4b900afa55d3f9cc5eebb6
SQL update if exist, else inser ยท GitHub
The ON DUPLICATE KEY UPDATE clause is used for the "if exists update else insert" operation. The forceWrite flag controls whether to force an update even if the sponsor is the same.
๐ŸŒ
Reddit
reddit.com โ€บ r/sql โ€บ [mysql] is there a way to do "insert if a record doesn't already exist with this value" ?
r/SQL on Reddit: [MySQL] Is there a way to do "insert if a record doesn't already exist with this value" ?
October 3, 2021 -

Hi all

Let's imagine I am keeping track of marathon runners. They all have a unique number on their chest, so I will use this number as their name.

So when I see the runner for the first time, I need to insert their details into the database. If I see the same runner again, I only want to insert their details if they haven't already been inserted.

Currently this is a two step process for me:

select id from runners where code = their_code;
*if no result*
    insert into runners (code) values (their_code);

But is there I way I can turn it into something like this:

insert into runners (code) values (their_code) if their_code not already in table

And ideally this would be much faster than two queries. Do you know what I mean?

Any help appreciated.

Thanks!

๐ŸŒ
Atlassian
atlassian.com โ€บ data โ€บ admin โ€บ how-to-insert-if-row-does-not-exist-upsert-in-mysql
Upsert Techniques in MySQL: INSERT If Not Exists | Atlassian
Learn to insert rows in MySQL only if they don't exist. Explore techniques like INSERT IGNORE, REPLACE, and ON DUPLICATE KEY UPDATE. Dive into the guide!
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 37504844 โ€บ mariadb-sql-trigger-to-update-if-key-exists-or-insert-if-doesnt-exist
mysql - MariaDB sql trigger to update if key exists or insert if doesn't exist? - Stack Overflow
CREATE TRIGGER key_access_monitor BEFORE INSERT ON individual_key_log FOR EACH ROW BEGIN IF EXISTS (SELECT reference_key FROM individual_key_log WHERE key = 'tester') SELECT 'Found it!' ELSE SELECT 'Cannot find it!' END IF END ... You want to insert a new row if a row with the same key does not already exist, and update the existing row if it does exist, is that correct?
๐ŸŒ
SitePoint
sitepoint.com โ€บ databases
MySql Table Insert if not exist otherwise update - Databases - SitePoint Forums | Web Development & Design Community
August 26, 2019 - CREATE TABLE `testing` ( `name` ... ADD id int NOT NULL AUTO_INCREMENT primary key; INSERT INTO testing (name) VALUES (1) ON DUPLICATE KEY UPDATE name= name+ 1; But it just creates new row every time....
Top answer
1 of 2
200

Use INSERT ... ON DUPLICATE KEY UPDATE. For example:

INSERT INTO `usage`
(`thing_id`, `times_used`, `first_time_used`)
VALUES
(4815162342, 1, NOW())
ON DUPLICATE KEY UPDATE
`times_used` = `times_used` + 1
2 of 2
7

I know this is an old question, but the Google lead me here recently so I imagine others come here, too.

@chaos is correct: there is the INSERT ... ON DUPLICATE KEY UPDATE syntax.

However, the original question asked about MySQL specifically, and in MySQL there is the REPLACE INTO ... syntax. IMHO, this command is easier and more straightforward to use for upserts. From the manual:

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.

Note this is not standard SQL. An example from the manual:

CREATE TABLE test (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  data VARCHAR(64) DEFAULT NULL,
  ts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id)
);

mysql> REPLACE INTO test VALUES (1, 'Old', '2014-08-20 18:47:00');
Query OK, 1 row affected (0.04 sec)

mysql> REPLACE INTO test VALUES (1, 'New', '2014-08-20 18:47:42');
Query OK, 2 rows affected (0.04 sec)

mysql> SELECT * FROM test;
+----+------+---------------------+
| id | data | ts                  |
+----+------+---------------------+
|  1 | New  | 2014-08-20 18:47:42 |
+----+------+---------------------+
1 row in set (0.00 sec)

Edit: Just a fair warning that REPLACE INTO isn't like UPDATE. As the manual says, REPLACE deletes the row if it exists, then inserts a new one. (Note the funny "2 rows affected" in the example above.) That is, it will replace the values of all columns of an existing record (and not merely update some columns.) The behavior of MySQL's REPLACE INTO is much like that of Sqlite's INSERT OR REPLACE INTO. See this question for some workarounds if you only want to update a few columns (and not all columns) if the record already exists.