Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: insert only new records

This must be very trivial but I can't seem to find the solution.

I work with two tables, both without any primary key.

I want to add all the records of the first table to the second table only if they don't exist.

Basically:

INSERT INTO Table2
SELECT Table1.*
FROM Table
WHERE "the record to be added doesn't already exists in Table2"
like image 733
Leo Avatar asked Apr 29 '26 06:04

Leo


1 Answers

You could do something like this. You would need to check each relevant column - I have just put in 2 as an example. With a Not Exists clause you can check if a record already existed across multiple columns. With a NOT IN you would only be able to check if a record already existed against one column.

INSERT INTO Table2
SELECT t1.*
FROM Table1 t1
WHERE NOT EXISTS 
(
      SELECT 1 
      FROM table2 t2 WHERE 
      t2.col1 = t1.col1 AND 
      t2.col2 = t1.col2
) 
like image 117
Donal Avatar answered Apr 30 '26 21:04

Donal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!