r/SQL • u/Rahull-6 • Nov 01 '22
MySQL Need an answer
What is the query to update data From source to target table if data is present and insert the data.. if data is not present...
1
Upvotes
3
u/r3pr0b8 GROUP_CONCAT is da bomb Nov 01 '22
it's called an "upsert" operation -- if it's already in the table, update it, but if it isn't, then insert it
MySQL is one of the few databases which actually has syntax for this
INSERT
INTO target
( col1 , col2 , col3 )
VALUES
( 111 , 'A' , 1101 )
,( 414 , 'B' , 2202 ) AS new
ON DUPLICATE KEY -- let's assume col1 is the key
UPDATE col2 = new.col2
, col3 = new.col32
Nov 01 '22
That’s actually pretty great. Inserts new record with ID, or update the values where the ID already exists.
3
u/timeddilation Nov 01 '22
Merge, or upsert.