MySQL insert ignore, on duplicate key update, with condition - mysql

I want to insert or update a record in a table. If it doesn't exist, it should be inserted. If it exists, then I only want to update the record if a certain condition is met. Is there a way to do this using a single INSERT statement? Something like this:
CREATE TABLE test1 SELECT 1 id, now() dt;
ALTER TABLE test1 ADD PRIMARY KEY (id);
INSERT IGNORE INTO test1 (id, dt) VALUES
(1, '2023-02-06 13:00:00')
ON DUPLICATE KEY UPDATE dt = VALUES(dt) WHERE dt = somedatetime;
-- i.e. always insert, but only update dt if existing dt value is something specific
I know I can do this using a transaction, I'm just wondering if something like this can be done in a single statement.

I was trying things out while writing the question and I found this to be one solution:
INSERT IGNORE INTO test1 (id, dt)
SELECT 1, '2023-02-06 13:00:00'
FROM test1
WHERE (NOT EXISTS(SELECT * FROM test1 WHERE id = 1))
OR (id = 1 AND dt = somedatetime)
ON DUPLICATE KEY UPDATE dt = VALUES(dt);

Related

Efficiency of Insert into on duplicate key update with many if expresssion

I'm trying to optimize the efficiency of one sql
it looks like:
Insert into order_table ( id, business_line, order_type,...)
values(1123123,4,5,·····)
ON DUPLICATE KEY UPDATE
business_line = IF( _version <= 6 ,10,business_line),
order_type = IF( _version <= 6 ,2,order_type)
..........
With many if condition
And it runs slow.(about 250ms)
Is there any way to bind so many 'if' together? Such as:
Insert into order_table ( id, business_line, order_type,...)
values(1123123,4,5,·····)
ON DUPLICATE KEY UPDATE
SET (business_line,order_type,...) =
IF( _version <= 6 ,(10,2),(business_line,order_type)),
..........
Any suggest will be appreciated
When the goal is to "UPDATE" several specific rows. Use a unique key (such as id):
INSERT INTO t
(id, a,b,c)
VALUES
(654, 1,2,3),
(666, 11,22,33),
...
ON DUPLICATE KEY UPDATE
b = VALUES(b),
c = VALUES(c);
When the goal is to "INSERT" several new rows. Don't supply any unique value (such as an AUTO_INCREMENT id):
INSERT INTO t
(id, a,b,c)
VALUES
(NULL, 1,2,3),
(NULL, 11,22,33),
...
ON DUPLICATE KEY UPDATE
b = VALUES(b);
Equivalently, leave out the AUTO_INCREMENT column and the NULLs.
Note: Version 8.0 wants this syntax instead:
b = NEW.b
(Caveat: Test this in your environment; I have not experimented with all variations.)
This technique should be faster because:
Only one roundtrip to the server
If autocommit=ON, then only one transaction for the batch.

MYSQL Check for duplicates and only insert if another field is a certain value

If I'm inserting data into a table with the following fields:
serialNumber active country
I need to only insert duplicate serialNumbers if active is no.
So for example: I want to insert a record with serialNumber 1234.
If the serial number doesn't already exist in the table go ahead and add it. If it does already exist, check the value of 'active' active is yes then don't add the new record, if it's no then do add the record.
Any ideas how to achieve this in MYSQL?
If the table lacks the necessary unique keys and you do not have permission, or don't want to set the keys you would need, you can use this alternative:
INSERT INTO `table1`
(`field1`,
`field2`)
SELECT value1,
value2
FROM (SELECT 1) t_1
WHERE NOT EXISTS (SELECT 1
FROM `table1`
WHERE `field1` = value1
AND `field2` = value2);
For yor question it could be written as
INSERT INTO `activity`
(`serialNumbers`,
`active`)
SELECT 1234,
'yes'
FROM (SELECT 1) t_1
WHERE EXISTS (SELECT 1
FROM `activity`
WHERE `serialNumbers` = 1234
AND `active` = 'no');
You can use the ON DUPLICATE KEY statement after an INSERT INTO query to update the row if it already exists. Documentation : https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
INSERT INTO table (serialNumber , active, country) VALUES (1010, 'no', 'FR')
ON DUPLICATE KEY UPDATE active='yes';
You can use the insert ... on duplicate key update in MySQL. It is similar to the MERGE used in other SQL databases, but MySQL does not provide the MERGE statement so this is the next best.
INSERT INTO TABLE (serialNumber, active, country)
VALUES (1234, 'active', 'GB') ON DUPLICATE KEY UPDATE country = 'ND';
Also, use INSERT IGNORE if you don't want to generate errors.

Mysql query to update row if exists?

I need an If, then, else query in mysql,
tried out the below,
if exists( select * from data_table where user_id =1 and link_id = 1) then update data_table set is_view = 1 where user_id = 1 else insert into data_table...
what is the correct way to do this?
if you only need to do this in mysql, then search insert on duplicate key. Or you can use a stored procedure. Check INSERT ... ON DUPLICATE KEY UPDATE Syntax
insert into data_table (user_id, link_id, other_column)
values (1, 1, 'value to insert or uodate')
on duplicate key update other_column='value to insert or update';

How to insert values from a table only if they do not exist already using mysql?

I am trying to read value from a table them insert it into another table only if the staring that I am trying to insert does not already exist in the table.
I have tried to use the ON DUPLICATE KEY clause but I get a syntax issue that i am unable to fix.
this is my query
SELECT Field1 FROM RSF
INSERT INTO result_codes(result_code_title, created_by)
VALUES (Field1, '2')
ON DUPLICATE KEY UPDATE result_code_title = Field1;
The clause is INSERT INTO ... SELECT and not SELECT ... INSERT INTO. Therefore:
INSERT INTO result_codes( result_code_title, created_by )
SELECT Field1, '2'
FROM RSF
ON DUPLICATE KEY
UPDATE result_code_title = Field1;
I think that should work.
Since you only want to insert only if the string doesn't already exist; you should be better off using INSERT INGORE:
INSERT IGNORE INTO result_codes( result_code_title, created_by )
SELECT Field1, '2'
FROM RSF
Use INSERT IGNORE instead.
INSERT IGNORE INTO result_codes(result_code_title, created_by)
SELECT Field1, '2'
FROM RSF
It detects via a primary key or unique index, if a row already exists and doesn't attempt to insert if this is the case.

MySQL Single Table Scan Update

Is there a way to accomplish a single table scan in MySQL with an UPDATE? The following is a standard example:
IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
INSERT INTO Table1 VALUES (...)
This is the ideal situation I'd like to happen in MySQL (But this is MsSQL):
UPDATE user SET (name = 'jesse') WHERE userid ='10001'
IF ##ROWCOUNT=0
INSERT INTO user (name) VALUES('jeeeeee')
It's sort of reversed in MySQL. You perform the insert, and if the key already exists, then update the row:
INSERT INTO Table1 (col1,col2,col3) VALUES (val1,val2,val3)
ON DUPLICATE KEY UPDATE col1 = val1, col2 = val2, col3 = val3;
This is predicated on you having a unique key for the table (which you do, right?)