HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

INSERT INTO without duplicates

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
intowithoutinsertduplicates

Problem

I want to do this

INSERT INTO AdminAccounts (Name) 
SELECT Name
FROM Matrix


But I don't want to create duplicates. ie, I ran this a few weeks ago and need to update the data.

Solution

This will insert new Name fields that were not previously in the Matrix table.

INSERT IGNORE
INTO AdminAccounts (Name) 
SELECT Name
FROM Matrix;


If you do not trust INSERT IGNORE, there is an alternative where you can manifest the new Name values before inserting them:

CREATE TABLE NewName SELECT Name FROM Matrix WHERE 1=2;
INSERT INTO NewName
    SELECT Name FROM AdminAccounts A
    LEFT JOIN Matrix B USING (Name)
    WHERE B.Name IS NULL;
INSERT INTO Matrix (Name) SELECT Name FROM NewNames;


The table NewName collects only those tables in AdminAccounts that are not in Matrix at present. This can give you a chance to look over the new Names. Afterwards, you can INSERT everything in NewName into Matrix.

Code Snippets

INSERT IGNORE
INTO AdminAccounts (Name) 
SELECT Name
FROM Matrix;
CREATE TABLE NewName SELECT Name FROM Matrix WHERE 1=2;
INSERT INTO NewName
    SELECT Name FROM AdminAccounts A
    LEFT JOIN Matrix B USING (Name)
    WHERE B.Name IS NULL;
INSERT INTO Matrix (Name) SELECT Name FROM NewNames;

Context

StackExchange Database Administrators Q#9689, answer score: 7

Revisions (0)

No revisions yet.