How to insert Distinct Records from Table A to Table B (both tables have same structure)
Asked Answered
F

4

7

I want to insert only Distinct Records from Table "A" to Table "B". Assume both the tables has same structure.

Friarbird answered 2/3, 2011 at 17:46 Comment(1)
By Distinct do you mean only records that don't exist in table B? Do you mean records that only occur once in Table A? Be more specific, and tell us what RDBMS you are using.Divulge
L
10

If by DISTINCT you mean unique records that are on TableB that aren't already in TableA, then do the following:

INSERT INTO TableB(Col1, Col2, Col3, ... , Coln)
SELECT DISTINCT A.Col1, A.Col2, A.Col3, ... , A.Coln
FROM TableA A
LEFT JOIN TableB B
ON A.KeyOfTableA = B.KeyOfTableB
WHERE B.KeyOfTableB IS NULL
Lardon answered 2/3, 2011 at 18:11 Comment(0)
S
9
INSERT INTO B SELECT DISTINCT * FROM A

You might not want the id column of the table to be part of the distinct check, so use this solution if that's the case: https://mcmap.net/q/1395942/-how-to-insert-distinct-records-from-table-a-to-table-b-both-tables-have-same-structure

Succussion answered 2/3, 2011 at 17:48 Comment(0)
P
6
INSERT INTO TableB
    (Col1, Col2, ...)
    SELECT DISTINCT Col1, Col2, ...
        FROM TableA
Polinski answered 2/3, 2011 at 17:47 Comment(1)
Yes. This is the query to use. Not the one by TheJubilex.Insouciance
I
1
    INSERT INTO TableB
            SELECT *
            FROM TableA AS A
            WHERE NOT EXISTS(SELECT * FROM TableB AS B WHERE B.Field1 = A.Field1) 
-- If need: B.Field2 = A.Field2 and B.Field3 = A.Field3
Isola answered 17/7, 2017 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.