dopplesoldner
dopplesoldner

Reputation: 9499

SQL - Check if all the columns in one table also exist in another

I have 2 tables (say A and B) in a MS SQL DB representing customer transactions. Both share a column (say Column X).

Ideally information in table B is a subset of information in table A.

Can I run a SQL query to check based on Column X if all the values in Table B are present in Table A?

Thanks

Upvotes: 2

Views: 2672

Answers (2)

Joe Stefanelli
Joe Stefanelli

Reputation: 135888

Here's the check to see if any table B rows are missing from table A.

SELECT b.*
    FROM Table_B b
    WHERE NOT EXISTS(SELECT 1
                         FROM Table_A a
                         WHERE a.x = b.x);

Upvotes: 3

juergen d
juergen d

Reputation: 204894

select X
from A
LEFT OUTER JOIN B on A.x = B.X
WHERE B.X IS NULL

to get all records from table A that are not in table B. Or

select X
from B
LEFT OUTER JOIN A on A.x = B.X
WHERE A.X IS NULL

to get all records from table B that are not in table A.

Upvotes: 3

Related Questions