With no sample data it is hard to say for sure, but my best guess would be that you have a NULL
value in table_A.Column1
. if you did have a null values, your query would be equivalent to something like:
SELECT Column1
FROM Table_B
WHERE Column1 NOT IN (1, 2, 3, NULL);
Which is equivalent of:
SELECT Column1
FROM Table_B
WHERE Column1 <> 1
AND Column1 <> 2
AND Column1 <> 3
AND Column1 <> NULL;
Since Column1 <> NULL
is not true, the query returns no results. The most syntactically similar way to achieve the desired result where you might have NULL columns is using NOT EXISTS
:
INSERT INTO Table_A(column1)
SELECT Column1
FROM Table_B AS B
WHERE NOT EXISTS (SELECT 1 FROM Table_A AS A WHERE A.Column1 = B.Column1);
However, another method you could use is:
INSERT INTO Table_A(column1)
SELECT Column1
FROM Table_B AS B
LEFT JOIN Table_A AS A
ON A.Column1 = B.Column1
WHERE A.Column1 IS NULL;
In this by left joining to table_A
then stating that A.Column1
has to be NULL
, you are removing any records that already exist in Table_A
.
I prefer the former (NOT EXISTS
), because I think the intent is much more clear, but if you use MySQL the latter will perform better
Or you could also use:
INSERT INTO Table_A(column1)
SELECT Column1
FROM Table_B AS B
WHERE B.Column1 IS NOT NULL
AND B.COlumn1 NOT IN (SELECT A.Column1 FROM Table_A AS A WHERE A.Column1 IS NOT NULL);