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 Overflowsql - IF NOT EXISTS - Mariadb Syntax - Stack Overflow
MySql Table Insert if not exist otherwise update - Stack Overflow
sql - How can I do 'insert if not exists' in MySQL? - Stack Overflow
mysql - If exists then update else insert - Database Administrators Stack Exchange
Use INSERT ... ON DUPLICATE KEY UPDATE
QUERY:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name="A", age=19
Check out REPLACE:
REPLACEworks exactly likeINSERT, except that if an old row in the table has the same value as a new row for aPRIMARY KEYor aUNIQUEindex, the old row is deleted before the new row is inserted.
Example:
REPLACE INTO `tablename` (`id`, `name`, `age`) VALUES (1, "A", 19)
The proper way to do this is using insert ... on duplicate key update. I would write the query as:
INSERT INTO valuation (ticker, depot_id, src_id, valuation_date, value)
VALUES ('BK001EUR', 1, 2, '2009-09-09', 14999260.46)
ON DUPLICATE KEY UPDATE value = VALUES(value);
(Note the use of VALUES() so you don't have to repeat the input.)
For this to work, you need a unique index on the keys you care about:
create unique index unq_valuation_4 on valuation(ticker, depot_id, src_id, valuation_date);
The duplicate key does not need to be the primary key index.
It can be any unique index.
You could use:
-- if exists then it will update
UPDATE valuation
SET value =14999260.46
WHERE ticker = 'BK001EUR'
AND depot_id =1 AND src_id =2 AND valuation_date ='2009-09-09';
-- if not exist then insert
INSERT INTO valuation (ticker,depot_id,src_id,valuation_date,value)
SELECT 'BK001EUR',1,2,'2009-09-09',14999260.46
-- FROM dual
WHERE NOT EXISTS (SELECT 1
FROM valuation
WHERE ticker = 'BK001EUR'
AND depot_id =1
AND src_id =2 AND valuation_date ='2009-09-09');
db<>fiddle demo
Or better way INSERT ON DUPLICATE UPDATE:
INSERT INTO valuation (ticker,depot_id,src_id,valuation_date,value)
VALUES ('BK001EUR',1,2,'2009-09-09',14999260.46)
ON DUPLICATE KEY UPDATE value =14999260.46;
Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE.
Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES() function to make sure the proper values are used when updating the other columns.
Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE syntax for MySQL:
INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE
Timestamp=VALUES(Timestamp)
Try using this:
If you specify
ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in aUNIQUE index orPRIMARY KEY, MySQL performs anUPDATE` of the old row...The
ON DUPLICATE KEY UPDATEclause can contain multiple column assignments, separated by commas.With
ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify theCLIENT_FOUND_ROWSflag tomysql_real_connect()when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...
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:
- repeated executions of the pipeline will not destroy our > database
- 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 UPDATEsyntax, 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.
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.
Only problem is, you can't use it like a normal query. Control structures like IF or WHILE are only allowed in stored procedures or functions.
Just create a procedure like this:
delimiter $$
create procedure select_or_insert()
begin
IF EXISTS (select * from users where username = 'something') THEN
update users set id= 'some' where username = 'something';
ELSE
insert into users (username) values ('something');
END IF;
end $$
delimiter ;
and call it like this:
call select_or_insert();
and Done
Hope This helps, DUPLICATE KEY UPDATE
create table machine(
machine_id int not null primary key,
machine_name varchar(50),
reg_id int
);
insert into machine (machine_id, machine_name, reg_id)
values(1, 'my_machine', 1);
INSERT INTO machine (reg_id, machine_id, machine_name) VALUES (1, 1, 'test_machine')
ON DUPLICATE KEY UPDATE machine_name=VALUES(machine_name);
Work on SQL Fiddle
INSERT INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock)
VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')
ON DUPLICATE KEY UPDATE col_1 = VALUES(col_1), col_2 = VALUES(col_2), col_3 = VALUES(col_3), col_4 = VALUES(col_4), col_5 = VALUES(col_5), col_6 = VALUES(col_6), unit = VALUES(unit), add_info = VALUES(add_info), fsar_lock = VALUES(fsar_lock)
Would work with tbl_id and row_nr having UNIQUE key.
This is the method DocJonas linked to with an example.
Here is the link to documentation INSERT ... ON DUPLICATE Statement.
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.
Create a
UNIQUEconstraint on yoursubs_emailcolumn, if one does not already exist:ALTER TABLE subs ADD UNIQUE (subs_email)Use
INSERT ... ON DUPLICATE KEY UPDATE:INSERT INTO subs (subs_name, subs_email, subs_birthday) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE subs_name = VALUES(subs_name), subs_birthday = VALUES(subs_birthday)
You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE - dev.mysql.com
- Note that I have used parameter placeholders in the place of string literals, as one really should be using parameterised statements to defend against SQL injection attacks.
Try this:
INSERT INTO `center_course_fee` (`fk_course_id`,`fk_center_code`,`course_fee`) VALUES ('69', '4920153', '6000') ON DUPLICATE KEY UPDATE `course_fee` = '6000';
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!
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
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.